Based on $ .ajax () method to get several ways to get JSON data from the server

One. What is JSON

JSON is a data structure that replaces XML, compared to XML, but it is smaller but the description ability is very strong, and the network transmission data is less traffic, and the speed is faster.

JSON is a string of strings, using the following symbols.

{key value pair}: JSON object

: json array

“: Double quotation marks are attribute or value

:: Before the colon, the key is the value (this value can be the value of the basic data type, or the array or object), so {“age”: 18} can be understood as a containing AGE 18 JSON objects, and [{“AGE”: 18}, {“AGE”: 20}] means a JSON array containing two objects. You can also simplify the above JSON array using {“age”: [18, 20]}, which is an object with an AGE array.

II. $ .ajax () method in the DataType property

$. Ajax () method requires the data type of the String type, and the data type that is expected to return. If not specified, jQuery will automatically return to ResponseXML or responseText [Interpretation] in Part III to return according to the HTTP package MIME information, and passed as a callback function parameter. The types available are as follows: XML: Returns an XML document, which can be processed using jQuery.

HTML: Returns the pure text HTML information; the included Script tag is executed when the DOM is inserted.

Script: Return to the plain text JavaScript code. Will not automatically cache the result. Unless the cache parameter is set. Note When the remote request (not in the same domain), all POST requests will be converted to the GET request.

JSON: Returns JSON data.

JSONP: JSONPFormat. When calling a function using SONP, such as MyURL? Callback = ?, jQuery will automatically replace a “?” As the correct function name to perform the callback function.

Three. MIME Data Type and Response’s setContentType () method

What is the MIME type? When transmitting the output result, the browser must start the appropriate application to process this output document. This can be done through a variety of type MIMEs (Multi-Fun INSA expansion protocol). In HTTP, the MIME type is defined in Content-Type Header.

For example, erect you want to transfer a Microsoft Excel file to the client. Then the MIME type at this time is “Application / VND.MS-Excel”. In most actual conditions, this file will then be sent to Execl (assuming that we sets Execl to handle special MIME type applications). In Java, the method for setting the MIME type is the ContentType property of the Response object. For example, use: response.setContentType (“text / html; charset = UTF-8”) is set.

In the earliest HTTP protocol, there is no additional data type information, all transmitted data is interpreted by the client as a hypertext tag language HTML document, and in order to support multimedia data types, the HTTP protocol is used. Additional MIME data type information before the document identifies the data type.

Each MIME type consists of two parts, the front is the large category of data, such as text text, image image, etc., which defines the specific type later.

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

ordinary text.txt text / plain

RTF text.RTF Application / RTF

GIF graphic. Gif Image / GIF

JPEG graphic.ipeg, .jpg image / jpeg

AU sound file .au Audio / Basic

MIDI music file MID, .MIDI AUDIO / MIDI, AUDIO / X-MIDI

ReaRaudio 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 the client receives data from the server, it is only accepting data streams from the server, and does not understand the name of the document, so the server must use additional information to tell the client data MIME type.

The server must first send the MIME type of flag data before sending real data. This information uses the Content-Type keyword to define, for example, for HTML documents, the server will first send the following two lines MIME Identification information, this identification is not part of the real data file.

Content-Type: Text / HTML

Note that the second behavior is a blank line, which is necessary, the purpose of using this space is to separate the MIME information with the true data content open.

As mentioned earlier, in Java, the method of setting the MIME type is the ContentType property of the response object, the method of setting is to use the response.setContentType (MIME) statement, responsE.SETCONTENTTYPE (MIME) The role is to distinguish the client browser, distinguish between different types of data, and process the corresponding data based on different program embedding modules in the browser in different MIMEs.

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

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

response.setContentType (“text / place; charSet = UTF-8”) Text

Application / JSON JSON Data

This method sets the content type of the response sent to the client, and the response is not submitted yet. The given content type can include character encoding description, for example: text / html; charSet = UTF-8. If the method is called before the getWriter () method is called, the response character encoding will only be set from the given content type. This method If the getWriter () method is called or after being submitted, the character encoding will not be set, and in the case of using the HTTP protocol, the method sets the Content-Type entity header.

Four. Use the $ .ajax () method to get the three ways of JSON data

The configuration of the DataType parameter determines how jQuery helps us automatically resolve the data returned by the server, and there are several ways to get JSON returned in the background. String and resolved to JSON objects, the following is Java as an example, the result of the following three mode is shown in Figure 1, the project is running in the inside network, the screenshot can only take pictures, forgive me.

1, $. Ajax () dataType parameter is not provided, the background response return type is not set, the default will be processed in plain text [respoNSE.SETCONTENTTYPE (“text / html; charset = UTF-8”); also as text processing], JS needs to manually use Eval () or $ .parsejson () and other methods to convert the returned string to JSON objects.

// Java Code: Get Background single NC locator history table data 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 deficename = 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.Println (Jsonarray.FromObject (SinglehistoryData) .tostring ()); // Print: [{“Time”: “2016-11-11 10:00:00”, “State”: “Run”, ” “:” Lock “, ….}, {” Time “:” 2016-11-11 10:00:05 “,” State “:” Run “,” Ball “:” Lock “,. …}, {}, {} ….] Check a few SinglehistoryData objects to print a few objects {“Time”: “2016-11-11 10:00:05”, “State”: “Run”, “Ball”: “Lock”, ….} response.Getwriter (). Print (Jsonarray.FromObject (SinglehistoryData) .tostring ());}

/ * JS code: Select the data query a certain period of time, click the query to display * / $ (“# search”). Click (function () {var data1 = []; var n; var deficename = $ (“body”). attr (“id”); var startdate = $ (“# startdate”). Val (); var enddate = $ (“# Enddate”). Val (); $ .ajax ({URL: “/ avvii / chart / gethistorysingledata”, type: “post”, data: {“device”: devices, “startdate”: startdate, “enddate”: endDate}, success (data); // —-> Pop-up [{“Time”: “2016-11-11 10:00:00”, “State”: “Run”, “Ball”: “Lock”, ….}, {“Time”: “2016-11-11 10:00:05”, “State”: “Run”, “Ball”: “Lock”, ….}, {}, {} ….], the background pass several SinglehistoryData objects to print the information of several objects {“Time”: “2016-11-11 10:00:05″, ” State “:” Run “,” Ball “:” Lock “, ….} alert (object.prototype.tostring.call (data)); // —> Pop-up [Object String], explain it Is string type data var jsonobjs = EVAL (“(” + Data + “)”); // or: var jsonobjs = $ .parsejson (data); Alert (jsonobjs); // alert (jsonobjs); -> Pop | [Object Object], [Object Object], [Object Object], [Object Object], [Object Object] …… Background pass several SinglehistoryData objects to print a few [object object] n = JSONOBJS.LENGTH; if (n == 0) {ALERT (“You have no data, please re-query”);} for (var i = 0; i 基于$.ajax()方法从服务器获取json数据的几种方式总结

2, $. Ajax () parameter Set DATatype = “json”, jQuery will automatically turn the returned string into JSON objects. The background can be set to: [Recommended] Response.setContentType (“text / html; charset = UTF-8”); or response.setContentType (“Application / JSON; Charset = UTF-8”);
   
// Java Code: Get background single NC locator history table data 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 deficename = 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”: “2016-11-11 10: 00:00, “State”: “Run”, “Ball”: “Lock”, ….}, {“Time”: “2016-11-11 10:00:05”, “State”: “Run”, “Ball”: “Lock”, ….}, {}, {} ….] Checks several SinglehistoryData objects to print the information of several objects {“Time”: “2016- 11-11 10:00:05 “,” State “:” Run “,” Ball “:” Lock “, ….} response.getwriter (). Print (jsonarray.FromObject (SinglehistoryData) .tostring ()
  / * JS code: When the page is loaded, the data of the specified time period is displayed * / var data1 = [] VAR DeviceName = $ ("body"). Attr ("ID"); var startdate = $ ("# startdate"). VAL ("2000-01-01 00:00:00); var enddate = $ ( "#nddate"). 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); // ----> Pop-up [Object Object], [Object Object] [Object Object], [Object Object], [Object Object] ... The background passed a few SinglehistoryData objects Several JSON objects: [object object] for (var i = 0; i < JsonObjs.length; i++){	      
		  	  var name = JsonObjs[i]['time'];//针对每一条数据:JsonObjs[i],或者: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};//个数与下面表头对应起来就可以了,至于叫什么名字并不影响控件的使用
    }
 		 if(JsonObjs.length != 10){
 			 for(var j=0;j<(10-((JsonObjs.length)%10));j++){    //补全最后一页的空白行,使表格的长度保持不变
 				 data1[j+JsonObjs.length] = {name:" ",state:"",ball:"",xd:"",yd:"",zd:"",xf:"",yf:"",zf:""}; 
 			 }
 		 }
    var userOptions = {
      "id":"kingTable",        				//必须 表格id
      "head":["时间","运行状态","球头状态","X向位置/mm","Y向位置/mm","Z向位置/mm","X向承载力/Kg","Y向承载力/Kg","Z向承载力/Kg"], //必须 thead表头
      "body":data1,         				//必须 tbody 后台返回的数据展示
      "foot":true,         					// true/false 是否显示tfoot --- 默认false
      "displayNum": 10,        					//必须 默认 10 每页显示行数
      "groupDataNum":6,        					//可选 默认 10 组数
      sort:false,         					// 点击表头是否排序 true/false --- 默认false
      search:false,         					// 默认为false 没有搜索
      lang:{
       gopageButtonSearchText:"搜索"
      }
    }
    var cs = new KingTable(null,userOptions);
   }
  }); 
 }); 

3, the AJAX method parameter does not specify DATATYPE, the background setting return type is “Application / “JSON”. This jQuery will intelligently determine according to the MIME type, and automatically resolve into JSON objects.

// java code: Background Get a historical form of a single CNC locator data public void getHistorySingleData () throws IOException {HttpServletRequest request = ServletActionContext.getRequest (); HttpServletResponse response = ServletActionContext.getResponse (); response.setHeader ( “Content-type”, “text / html; charset = UTF-8”) Response.setContentType (“Application / JSON; Charst = 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”: ” 2016-11-11 10:00:00 “,” State “:” Run “,” Ball “:” Lock “, ….}, {” TIME “:” 2016-11-11 10:00: 05 “,” State “:” Run “,” Ball “:” Lock “, ….}, {}, {} ….] Checks Several SingleHistoryData objects to print several objects { “Time”: “2016-11-11 10:00:05”, “State”: “Run”, “Ball”: “Lock”, ….} response.getwriter (). print (jsonarray.fromObject) (SINGLEHISTORYDATA);}
  / * JS code: When the page is first loaded, the data specified time period is displayed. * / VAR DATA1 = []; var deficename = $ ("body"). Attr ("ID"); var startdate = $ ("# startdate"). VAL ("2000-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"}, Success: function (data) { Alert (data); // ----> Pop-up [Object Object], [Object Object] [Object Object], [Object Object], [Object Object] ... The background passed several SinglehistoryData objects Just print a few JSON objects: [Object object] for (var i = 0; i  
Note As long as the front desk or the background has a return JSON object, there is no need Using an eval () method or $ .parsejson () method parsing, resolution is wrong.
 Summary: In the above way, it is recommended to use the second way, convenient and not easy to erode.  < 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++){    //补全最后一页的空白行,使表格的长度保持不变
				 data1[j+data.length] = {name:" ",state:"",ball:"",xd:"",yd:"",zd:"",xf:"",yf:"",zf:""}; 
			 }
		 }
   var userOptions = {
     "id":"kingTable",        				//必须 表格id
     "head":["时间","运行状态","球头状态","X向位置/mm","Y向位置/mm","Z向位置/mm","X向承载力/Kg","Y向承载力/Kg","Z向承载力/Kg"], //必须 thead表头
     "body":data1,         				//必须 tbody 后台返回的数据展示
     "foot":true,         					// true/false 是否显示tfoot --- 默认false
     "displayNum": 10,        					//必须 默认 10 每页显示行数
     "groupDataNum":6,        					//可选 默认 10 组数
     sort:false,         					// 点击表头是否排序 true/false --- 默认false
     search:false,         					// 默认为false 没有搜索
     lang:{
      gopageButtonSearchText:"搜索"
     }
   }
   var cs = new KingTable(null,userOptions);
  }
 });  
5. Eval () method

VAR JSON object = EVAL (‘(‘ + JSON data + ‘)’); Coached content enclosed by EVAl () The execution is returned is a JSON object.

EVAL function Working principle: The EVAL function evaluates a given string containing JavaScript code, and attempts to perform an expression in a string or a series of legitimate JavaScript statements. The EVAL function will use the value contained in the last expression or state as a return value.
 Why is EVAL to add "(" ("+ Data +") "); //"?   
The reason is: EVAL itself problem. Since JSON starts and ends in the “{}”, in JS, it will be handled as a statement block, so it must be mandatory to convert it into an expression. Plus the purpose of parentheses is to force the EVAL function to force the expression (Expression) of parentheses to be converted to an object while processing JavaScript code, not as a statement (Statement). For example, if the object word is {}, if the kettler is not added, the eVal recognizes the braces as the beginning and end tag of the JavaScript code block, then {} will be considered to be a novel statement.
The above is based on the $ .ajax () method from the server to obtain JSON data, the summary is the full content of Xiaobian sharing, I hope to give you a reference, I hope everyone can support Tumi. cloud.
                    
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment