Summary of several ways to obtain json data from the server based on the $. ajax () method,. ajaxjson

Source: Internet
Author: User

Summary of several ways to obtain json data from the server based on the $. ajax () method,. ajaxjson

1. What is json

Json is a data structure that replaces xml. Compared with xml, json is more compact but has a strong descriptive capability, and uses less traffic to transmit data over the network, which is faster.

Json is a string marked with the following symbol.

{Key-Value Pair}: json object

[{},{},{}]: Json Array

"": Double quotation marks are attributes or values.

: The key before the colon, and the value after the colon (this value can be a value of the basic data type, or an array or an object), So {"age ": 18} is a json object containing age 18, and [{"age": 18}, {"age ": 20}] indicates a json array containing two objects. You can also use {"age": []} to simplify the preceding json array. This is an object with an age array.

Ii. Value of the ype attribute in the $. ajax () method

The dataType attribute in the $. ajax () method must be a String-type parameter, which is the expected data type returned by the server. If this parameter is not specified, JQuery will automatically return responseXML or responseText [explained in Part 3] based on the mime information of the http package and pass it as a callback function parameter. The available types are as follows:

Xml: the XML document is returned and can be processed by JQuery.

Html: returns plain text HTML information. The included script tag is executed when the DOM is inserted.

Script: returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that during remote requests (not in the same domain), all post requests will be converted to get requests.

Json: Return JSON data.

Jsonp: JSONP format. When a function is called in the form of SONP, such as myurl? Callback = ?, JQuery will automatically Replace the last "?" For the correct function name to execute the callback function.

Iii. Mime data type and the setContentType () method of response

What is the MIME type? When sending the output result to a browser, the browser must start an appropriate application to process the output document. This can be done through multiple types of MIME (multi-function Internet Mail Extension protocol. In HTTP, the MIME Type is defined in the Content-Type header.

For example, you need to transfer a Microsoft Excel file to the client. The MIME type is "application/vnd. ms-excel ". In most cases, this file is then transmitted to Execl for processing (assuming we set Execl to an application that handles special MIME types ). In Java, the method for setting the MIME type is through the ContentType attribute 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 HTML documents in the hypertext markup language. to support multimedia data types, the MIME data type information appended to the document is used in the HTTP protocol to identify the data type.

Each MIME type consists of two parts. The front is a big data type, such as text, image, and so on. Specific types are defined later.

Common MIME types:

Hypertext markup language text .html, .html text/html

Common text. txt text/plain

RTF text. rtf application/rtf

GIF image. gif image/gif

JPEG image .ipeg,.jpg image/jpeg

Au audio file. au audio/basic

MIDI music files mid,. midi audio/midi, audio/x-midi

RealAudio music file. ra,. ram audio/x-pn-realaudio

MPEG file. mpg,. mpeg video/mpeg

AVI file. avi video/x-msvideo

GZIP file. gz application/x-gzip

TAR file. tar application/x-tar

When a customer program receives data from the server, it only accepts data streams from the server and does not know the document name. Therefore, the server must use additional information to tell the customer program the MIME type of data.

Before the server sends real data, it must first send the MIME type information of the Flag data. This information is defined using the Content-type keyword. For example, for HTML documents, the server will first send the following two lines of MIME identification information, which is not part of a real data file.

Content-type: text/html

Note that the second act is a blank line, which is required to separate the MIME information from the real data content.

As mentioned above, in Java, the method for setting the MIME type is to use the ContentType attribute of the Response object. The method for setting the MIME type is to use response. setContentType (MIME) Statement, response. setContentType (MIME) is used to enable the client browser to distinguish different types of data and call different program embedding modules in the browser based on different MIME types to process the corresponding data.

The installation directory \ conf \ web. xml of Tomcat defines a large number of MIME types. For details, refer. For example, you can set:

Response. setContentType ("text/html; charset = UTF-8"); html

Response. setContentType ("text/plain; charset = UTF-8"); text

Application/json data

This method sets the content type of the response sent to the client. At this time, the response has not been submitted. The given content type can include character encoding instructions, such as text/html; charset = UTF-8. If this method is called before the getWriter () method is called, the character encoding of the response is set only from the given content type. If this method is called after the getWriter () method is called or after the method is submitted, no response character encoding is set. When http is used, this method sets the Content-type object header.

4. Three methods for obtaining json data using the $. ajax () method

The configuration of the dataType parameter determines how jquery can help 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, the results of the three methods below are shown in Figure 1. The project runs on the Intranet and cannot be taken. You can only take photos. Sorry.

1. $. if dataType is not set in the ajax () parameter, and response type is not set in the background, the common text is processed by default. setContentType ("text/html; charset = UTF-8"); also used for text processing]. In js, You need to manually use eval () or $. parseJSON () and other methods to convert the returned string to a json object.

// Java code: Obtain the public void getHistorySingleData () throws IOException {HttpServletRequest request = ServletActionContext of the History Table of a single NC positioner in the background. 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 (); // print: [{"time": "10:00:00", "state": "run", "ball ": "Locking ",....}, {"time": "10:00:05", "state": "run", "ball": "locked ",....}, {},{}...] check several singleHistoryData objects and print the information of several objects. {"time": "10:00:05", "state": "run", "ball ": "Locking ",....} response. getWriter (). print (JSONArray. fromObject (singleHistoryData ). toString ());}
/* Js code: select to query data for a certain period of time, and click query to display */$ ("# 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": "20 16-11-11 10:00:00 "," state ":" run "," ball ":" locked ",....}, {"time": "10:00:05", "state": "run", "ball": "locked ",....}, {},{}...], after several singleHistoryData objects are uploaded in the background, the information of these objects is printed. {"time": "10:00:05", "state": "run", "ball ": "Locking ",....} alert (Object. prototype. toString. call (data); // ---> [object String] is displayed, indicating that the data of the String type is obtained. var JsonObjs = eval ("(" + data + ")"); // or: var JsonObjs = $. parseJSON (data); alert (JsonObjs ); // Alert (JsonObjs); ----> [object Object], [object Object], [object Object] [object Object], [object Object], [object Object]… Several singleHistoryData objects are uploaded in the background to print several [object objects] n = JsonObjs. length; if (n = 0) {alert ("no data for the selected time period, please query again") ;}for (var I = 0; I <JsonObjs. length; I ++) {var name = JsonObjs [I] ['time']; // For each piece of data: JsonObjs [I], or: JsonObjs [I]. time var state = JsonObjs [I] ['state']; var ball = JsonObjs [I] ['ball']; var xd = JsonObjs [I] ['xd ']; var yd = JsonObjs [I] ['yd ']; var zd = JsonObjs [I] ['zd']; var xf = JsonObjs [I] ['xf']; var Yf = JsonObjs [I] ['yf']; var zf = JsonObjs [I] ['zf ']; data1 [I] = {name: name, state: state, ball: ball, xd: xd, yd: yd, zd: zd, xf: xf, yf: yf, zf: zf }; // The number corresponds to the following header. The name does not affect the use of the control.} if (JsonObjs. length! = 10) {for (var j = 0; j <(10-(JsonObjs. length) % 10); j ++) {// complete the blank rows on the last page so that the table length remains unchanged. data1 [j + JsonObjs. length] = {name: "", state: "", ball: "", xd: "", yd: "", zd: "", xf :"", yf: "", zf: "" };}} var userOptions = {"id": "kingTable", // The table id "head": ["time ", "Running status", "ball head status", "X direction position/mm", "Y direction position/mm", "Z direction position/mm ", "X direction bearing capacity/Kg", "Y direction bearing capacity/Kg", "Z direction bearing capacity/Kg"], // The thead header must be "body": data1, // The data returned by the tbody background must be displayed as "foot": true, // true/false: whether to display tfoot --- default value: false "displayNum": 10, // The default value is 10. The number of lines displayed per page is "groupDataNum": 6. // optional. The default value is 10. sort: false. // click whether the header is sorted. true/false --- the default value is false. search: false, // The default value is false. lang: {gopageButtonSearchText: "Search" }}var cs = new KingTable (null, userOptions) ;}}) is not searched );}});});

2. If dataType = "json" is set in the $. ajax () parameter, jquery automatically converts the returned string to a json object. The backend can be set to: [recommended] response. setContentType ("text/html; charset = UTF-8"); or response. setContentType ("application/json; charset = UTF-8 ");

// Java code: Obtain the public void getHistorySingleData () throws IOException {HttpServletRequest request = ServletActionContext of the History Table of a single NC positioner in the background. 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 (); // print: [{"time": "10:00:00", "state": "run", "ball ": "Locking ",....}, {"time": "10:00:05", "state": "run", "ball": "locked ",....}, {},{}...] check several singleHistoryData objects and print the information of several objects. {"time": "10:00:05", "state": "run", "ball ": "Locking ",....} response. getWriter (). print (JSONArray. fromObject (singleHistoryData ). toString ());}
/* Js code: When the page is loaded for the first time, data within the specified time period is displayed */var data1 = []; var deviceName = $ ("body "). attr ("id"); var startDate = $ ("# startDate "). val ("00:00:00"); var endDate = $ ("# endDate "). val ("00:00:00"); $. ajax ({url: "/avvii/chart/getHistorySingleData", type: "post", data: {"deviceName": deviceName, "startDate": "00:00:00 ", "endDate": "00:00:00"}, dataType: "json", success: function (da Ta) {alert (data); // ----> [object Object], [object Object], [object Object] [object Object], [object Object], [object Object] ...... Several singleHistoryData objects are uploaded in the background to print several json objects: [object Object] for (var I = 0; I <data. length; I ++) {var name = data [I] ['time']; var state = data [I] ['state']; var ball = data [I] ['ball']; var xd = data [I] ['xd ']; var yd = data [I] ['yd']; var zd = data [I] ['zd']; var xf = data [I] ['xf']; var yf = data [I] ['yf']; var zf = data [I] ['zf ']; data1 [I] = {name: name, state: state, ball: ball, xd: xd, yd: yd, zd: zd, xf: xf, yf: yf, zf: zf };} If (data. length! = 10) {for (var j = 0; j <(10-(data. length) % 10); j ++) {// complete the blank rows on the last page so that the table length remains unchanged. data1 [j + data. length] = {name: "", state: "", ball: "", xd: "", yd: "", zd: "", xf :"", yf: "", zf: "" };}} var userOptions = {"id": "kingTable", // The table id "head": ["time ", "Running status", "ball head status", "X direction position/mm", "Y direction position/mm", "Z direction position/mm ", "X direction bearing capacity/Kg", "Y direction bearing capacity/Kg", "Z direction bearing capacity/Kg"], // The thead header must be "body": data1, // The data returned by the tbody background must be displayed as "foot": true, // true/false: whether to display tfoot --- default value: false "displayNum": 10, // The default value is 10. The number of lines displayed per page is "groupDataNum": 6. // optional. The default value is 10. sort: false. // click whether the header is sorted. true/false --- the default value is false. search: false, // The default value is false. lang: {gopageButtonSearchText: "Search" }}var cs = new KingTable (null, userOptions);} is not searched );}});

3. If dataType is not specified in the ajax method parameter, the return type is set to "application/json" in the background ". In this way, jquery intelligently determines Based on the mime type and automatically parses it into a json object.

// Java code: Obtain the public void getHistorySingleData () throws IOException {HttpServletRequest request = ServletActionContext of the History Table of a single NC positioner in the background. getRequest (); HttpServletResponse response = ServletActionContext. getResponse (); response. setHeader ("Content-type", "text/html; charset = UTF-8"); response. setContentType ("application/json; 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 (); // print: [{"time": "10:00:00", "state": "run", "ball ": "Locking ",....}, {"time": "10:00:05", "state": "run", "ball": "locked ",....}, {},{}...] check several singleHistoryData objects and print the information of several objects. {"time": "10:00:05", "state": "run", "ball ": "Locking ",....} response. getWriter (). print (JSONArray. fromObject (singleHistoryData ). toString ());}
/* Js code: When the page is loaded for the first time, data within the specified time period is displayed */var data1 = []; var deviceName = $ ("body "). attr ("id"); var startDate = $ ("# startDate "). val ("00:00:00"); var endDate = $ ("# endDate "). val ("00:00:00"); $. ajax ({url: "/avvii/chart/getHistorySingleData", type: "post", data: {"deviceName": deviceName, "startDate": "00:00:00 ", "endDate": "00:00:00"}, success: function (data) {alert (data); // ----> [Object Object], [object Object], [object Object] [object Object], [object Object object], [Object object Object]… Several singleHistoryData objects are uploaded in the background to print several json objects: [object Object] for (var I = 0; I <data. length; I ++) {var name = data [I] ['time']; var state = data [I] ['state']; var ball = data [I] ['ball']; var xd = data [I] ['xd ']; var yd = data [I] ['yd']; var zd = data [I] ['zd']; var xf = data [I] ['xf']; var yf = data [I] ['yf']; var zf = data [I] ['zf ']; data1 [I] = {name: name, state: state, ball: ball, xd: xd, yd: yd, zd: zd, xf: xf, yf: yf, zf: zf };} If (data. length! = 10) {for (var j = 0; j <(10-(data. length) % 10); j ++) {// complete the blank rows on the last page so that the table length remains unchanged. data1 [j + data. length] = {name: "", state: "", ball: "", xd: "", yd: "", zd: "", xf :"", yf: "", zf: "" };}} var userOptions = {"id": "kingTable", // The table id "head": ["time ", "Running status", "ball head status", "X direction position/mm", "Y direction position/mm", "Z direction position/mm ", "X direction bearing capacity/Kg", "Y direction bearing capacity/Kg", "Z direction bearing capacity/Kg"], // The thead header must be "body": data1, // The data returned by the tbody background must be displayed as "foot": true, // true/false: whether to display tfoot --- default value: false "displayNum": 10, // The default value is 10. The number of lines displayed per page is "groupDataNum": 6. // optional. The default value is 10. sort: false. // click whether the header is sorted. true/false --- the default value is false. search: false, // The default value is false. lang: {gopageButtonSearchText: "Search" }}var cs = new KingTable (null, userOptions);} is not searched );}});

Note: As long as there is a json object returned in the foreground or background, you do not need to use the eval () method or the $. parseJSON () method for parsing, and then the parsing will fail.

Conclusion: The second method is recommended for the above methods, which is convenient and error-free.

V. eval () method

Var json object = eval ('+ json Data +'); The content enclosed in braces is returned as a JSON object after eval () is executed.

How eval functions work: the eval function evaluates a given string containing JavaScript code and tries to execute expressions contained in the string or a series of legal JavaScript statements. The eval function uses the value or reference contained in the last expression or statement as the return value.

Why do you want to add "(" ("+ data +") "); //" to eval?

The reason is:Eval itself. Json starts and ends in the form of "{}". In JS, json is treated as a statement block. Therefore, it must be forcibly converted into an expression. The purpose of parentheses is to force the eval function to forcibly convert the expressions in parentheses into objects when processing JavaScript code, rather than executing them as statements. For example, if no outer brackets are added to the object literal {}, eval identifies the braces as the start and end mark of the JavaScript code block, then {} is considered to have executed an empty statement.

The above is based on $. the ajax () method is used to obtain json data from the server. The summary is all the content shared by the editor. I hope to give you a reference, and I hope you can provide more support for the customer's house.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.