How to get json data from the server using the $.ajax() method
This time I will show you how to get json data from the server using the $.ajax() method. What are the precautions for using the $.ajax() method to get json data from the server? The following is a practical case, let’s take a look.
one. What is json
json is a data structure that replaces xml. Compared with xml, it is smaller but has strong descriptive capabilities. It uses less traffic and is faster to transmit data over the network.
json is a string of characters, marked with the following symbols.
{key-value pair}: json object
[{},{},{}]: json array
"": The attribute or value within double quotes is
:: The colon is preceded by the key and followed by the value (this value can be a value of the basic data type, or an array or object), so {"age": 18} It can be understood as a json object containing age 18, and [{"age": 18},{"age": 20}] represents a json array containing two objects. You can also use {"age":[18,20]} to simplify the above json array, which is an object with an age array.
two. The value of the dataType attribute in the $.ajax() method
The dataType attribute in the $.ajax() method is required to be a String type parameter, which is the data type expected to be returned by the server. If not specified, JQuery will automatically return responseXML or responseText [explained in Part 3] based on the http package mime information, and pass it as the callback function parameter . The available types are as follows:
xml: Returns an XML document that can be processed with JQuery.
html: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.
script: Returns plain text JavaScript code. Results are not cached automatically. Unless cache parameters are set. Note that when making remote requests (not under the same domain), all post requests will be converted into get requests.
json: Returns JSON data.
jsonp: JSONP format. When calling a function using the SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.
three. Mime data type and response setContentType() method
What are MIME types? When transmitting output results to the browser, the browser must start the appropriate application to process the output document. This can be accomplished through various types of MIME (Multipurpose Internet Mail Extensions). In HTTP, MIME types are defined in the Content-Type header.
For example, suppose you want to send a Microsoft Excel file to client. Then the MIME type at this time is "application/vnd.ms-excel". In most practical cases, this file will then be transferred to Execl to handle (assuming we set Execl to handle special MIME types of applications). In Java, the way to set the MIME type is through the ContentType property of the Response object. For example, commonly used: response.setContentType("text/html;charset=UTF-8") to set.
In the earliest HTTP protocol, there was no additional data type information. All transmitted data was interpreted by the client program as a Hypertext Markup Language HTML document. In order to support multimedia data types, the HTTP protocol used MIME appended before the document. Data type information to identify the data type.
Each MIME type consists of two parts. The first part is the general category of data, such as text, image, etc., and the second part defines the specific type.
Common MIME types:
Hypertext Markup Language text .html,.html text/html
Plain text .txt text/plain
RTF text .rtf application/rtf
GIF graphics .gif image/gif
JPEG graphics .ipeg,.jpg image/jpeg
au sound file .au audio/basic
MIDI music files mid,.midi audio/midi,audio/x-midi
RealAudio music files .ra, .ram audio/x-pn-realaudio
MPEG files .mpg,.mpeg video/mpeg
AVI file .avi video/x-msvideo
GZIP file .gz application/x-gzip
TAR file .tar application/x-tar
When the client program receives data from the server, it only accepts the data stream from the server and does not know the name of the document, so the server must use additional information to tell the client program the MIME type of the data.
Before the server sends the real data, it must first send the MIME type information that marks the data. This information is defined using the Content-type keyword. For example, for an HTML document, the server will first send the following two lines of MIME identification information. This identification does not Not really part of the data file.
Content-type: text/html
Note that the second line is a blank line, which is necessary. The purpose of using this blank line is to separate the MIME information from the real data content.
As mentioned earlier, in Java, the way to set the MIME type is through the ContentType attribute of the Response object. The setting method is to use the response.setContentType(MIME) statement. The function of response.setContentType(MIME) is to make the client browser , distinguish different types of data, and call different program embedded modules in the browser according to different MIMEs to process the corresponding data.
A large number of MIME types are defined in confweb.xml, the installation directory of Tomcat, for reference. For example, you can set:
response.setContentType("text/html; charset=utf-8"); html
response.setContentType("text/plain; charset=utf-8"); text
application/json json data
This method sets the content type of the response sent to the client before the response is submitted. The content type given can include character encoding specifications, for example: text/html;charset=UTF-8. If this method is called before the getWriter() method is called, then the character encoding of the response will only be set from the given content type. If this method is called after the getWriter() method is called or after it is submitted, it will not set the character encoding of the response. In the case of using the http protocol, this method sets Content-type entity header.
Four. Three ways to obtain json data using the $.ajax() method
The configuration of the dataType parameter determines how jquery helps us automatically parse the data returned by the server. There are several ways to obtain the json string returned by the background and parse it into a json object. The following is an example of Java explaining the results of the following three methods
1. If the dataType is not set in the $.ajax() parameter, and the return type is not set in the background response, it will be processed as ordinary text by default [response.setContentType("text/html;charset=utf-8"); is also processed as text 】, in js you need to manually use eval() or $.parseJSON() and other methods to convert the returned string into a json object for use.
//Java代码:后台获取单个数控定位器的历史表格的数据 public void getHistorySingleData() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setContentType("text/html;charset=utf-8"); String deviceName = request.getParameter("deviceName"); String startDate= request.getParameter("startDate"); String endDate = request.getParameter("endDate"); SingleHistoryData[] singleHistoryData = chartService.getHistorySingleData(deviceName,startDate, endDate); System.out.println(singleHistoryData.length); System.out.println(JSONArray.fromObject(singleHistoryData).toString());//打印:[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....]查到几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....} response.getWriter().print(JSONArray.fromObject(singleHistoryData).toString()); }rrree
2. Set dataType="json" in the $.ajax() parameter, then jquery will automatically convert the returned string into a json object. The background can be set to: [Recommended] response.setContentType("text/html;charset=utf-8"); or response.setContentType("application/json;charset=utf-8");
/*js代码:选择查询某一时间段的数据,点击查询之后进行显示*/ $("#search").click(function () { var data1 = []; var n; var deviceName=$("body").attr("id"); var startDate = $("#startDate").val(); var endDate = $("#endDate").val(); $.ajax({ url:"/avvii/chart/getHistorySingleData", type:"post", data:{ "deviceName":deviceName, "startDate": startDate, "endDate": endDate }, success: function (data) { alert(data);//---->弹出[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....],后台传过来几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....} alert(Object.prototype.toString.call(data)); //--->弹出[object String],说明获取的是String类型的数据 var JsonObjs = eval("(" + data + ")"); //或者:var JsonObjs = $.parseJSON(data); alert(JsonObjs);//alert(JsonObjs);---->弹出[object Object],[object Object],[object Object][object Object],[object Object],[object Object]……后台传过来几条singleHistoryData对象就打印几个[object Object] n=JsonObjs.length; if(n==0){ alert("您选择的时间段无数据,请重新查询"); } for(var i = 0; i//Java代码:后台获取单个数控定位器的历史表格的数据 public void getHistorySingleData() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setContentType("text/html;charset=utf-8"); String deviceName = request.getParameter("deviceName"); String startDate= request.getParameter("startDate"); String endDate = request.getParameter("endDate"); SingleHistoryData[] singleHistoryData = chartService.getHistorySingleData(deviceName,startDate, endDate); System.out.println(singleHistoryData.length); System.out.println(JSONArray.fromObject(singleHistoryData).toString());//打印:[{"time":"2016-11-11 10:00:00","state":"运行","ball":"锁紧",....},{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....},{},{}....]查到几条singleHistoryData对象就打印几个对象的信息{"time":"2016-11-11 10:00:05","state":"运行","ball":"锁紧",....} response.getWriter().print(JSONArray.fromObject(singleHistoryData).toString()); }3. DataType is not specified in the ajax method parameters, and the return type is set to "application/json" in the background. In this way, jquery will intelligently judge based on the mime type and automatically parse it into a json object.
/*js代码:页面首次加载时,显示规定时间段的数据*/ var data1 = []; var deviceName=$("body").attr("id"); var startDate = $("#startDate").val("2000-01-01 00:00:00"); var endDate = $("#endDate").val("2018-01-01 00:00:00"); $.ajax({ url:"/avvii/chart/getHistorySingleData", type:"post", data:{ "deviceName":deviceName, "startDate": "2000-01-01 00:00:00", "endDate": "2018-01-01 00:00:00" }, dataType:"json", success: function (data) { alert(data);//---->弹出[object Object],[object Object],[object Object][object Object],[object Object],[object Object]……后台传过来几条singleHistoryData对象就打印几个json对象:[object Object] for(var i = 0; i rrree<p style="text-align: left;"> Note: As long as there is a setting to return a json object in the front or backend, there is no need to use the eval() method or $.parseJSON() method to parse, otherwise an error will occur when parsing again. </p><p style="text-align: left;"> <span style="background-color:#ccffcc;">Summary: Among the above methods, it is recommended to use the second method, which is convenient and less error-prone. </span> </p><p style="text-align: left;"> <span style="color:#ff0000;"><strong>five. eval() method</strong></span> </p><p style="text-align: left;"> var json object=eval('(' json data ')'); A JSON object is returned after the content enclosed in curly brackets is executed by eval(). </p><p style="text-align: left;"> How the eval function works: The eval function evaluates a given string containing JavaScript code and attempts to execute the expression or a series of legal JavaScript statements contained in the string. The eval function will return the value or reference contained in the last expression or statement. </p><p style="text-align: left;"> <span style="color:#ff00ff;"><strong> Why do we need to add "("(" data ")");//" to eval? </strong></span> </p><p style="text-align: left;"> <strong>The reason is: </strong>eval itself. Since json starts and ends with "{}", it will be processed as a statement block in JS, so it must be forced to be converted into an expression. The purpose of adding parentheses is to force the eval function to convert the expression in the parentheses into an object when processing JavaScript code, rather than executing it as a statement. For example, take the object literal {}. If no outer brackets are added, then eval will recognize the braces as the beginning and end marks of the JavaScript code block, and {} will be considered to execute an empty statement. </p><p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! </p><p>Recommended reading: </p><p><a href="http://www.php.cn/js-tutorial-392375.html" target="_blank">getBoundingClientRect usage and compatibility processing</a><br></p><p><a href="http://www.php.cn/js-tutorial-392373.html" target="_blank">detailed explanation of vue's implementation of the small ball parabolic effect of the shopping cart </a><br></p><p><a href="http://www.php.cn/js-tutorial-392370.html" target="_blank">Detailed explanation of the use of components in Vue.js</a><br></p><!--content end-->
The above is the detailed content of How to get json data from the server using the $.ajax() method. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software