JQuery Ajax Asynchronous processing JSON data instance detailed

Source: Internet
Author: User
Tags eval

Let's take a look at an official example.

Instance

Use AJAX requests to get JSON data and output the results:

The code is as follows Copy Code

$ ("button"). Click (function () {
$.getjson ("Demo_ajax_json.js", function (Result) {
$.each (result, function (i, field) {
$ ("div"). append (Field + "");
});
});
});

This function is shorthand for Ajax functions, equivalent to:

The code is as follows Copy Code

$.ajax ({
Url:url,
Data:data,
Success:callback,
Datatype:json
});

Data sent to the server can be appended to the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and URL-coded before being appended to the URL.

The return data passed to the callback can be a JavaScript object or an array defined in the JSON structure and parsed using the $.parsejson () method.

Example

Load JSON data from Test.js and display a name field data from the JSON data:

The code is as follows Copy Code

$.getjson ("Test.js", function (JSON) {
Alert ("JSON Data:" + json.users[3].name);
});

An example with ASP.net

First gives the JSON data to be passed: [{"Demodata": "This is the JSON data"}]
1, using the normal ASPX page to handle


I think this is the easiest way to deal with it, look at the code below

The code is as follows Copy Code
$.ajax ({


Type: "Post",


URL: "Default.aspx",


DataType: "JSON",


Success:function (data) {


$ ("Input#showtime"). Val (Data[0].demodata);


},


Error:function (XMLHttpRequest, Textstatus, Errorthrown) {


alert (Errorthrown);


}


});



This is the code that passes the data in the background

The code is as follows Copy Code

Response.Clear ();
Response.Write ("[{" Demodata ":" This is the JSON Data "}]");
Response.Flush ();
Response.End ();

This way of processing will pass over the data directly parsed into JSON data, that is, the foreground JS code here may be directly to parse the data into JSON object data, rather than string data, such as Data[0].demodata, here directly using this JSON object data
2, use WebService (ASMX) to process

This approach does not take the data passed over as a JSON object data, but rather as a string, as the following code

The code is as follows Copy Code

$.ajax ({
Type: "Post",
URL: "Jquerycsmethodform.asmx/getdemodata",
DataType: "JSON",/* This sentence can not be used, no impact * *

ContentType: "Application/json; Charset=utf-8 ",
Success:function (data) {
$ ("Input#showtime"). Val (eval (' + DATA.D + ') ') [0].demodata);

There are two ways to convert data, the effect of two ways is the same as//$ ("Input#showtime"). Val (eval (DATA.D) [0].demodata);

},
Error:function (XMLHttpRequest, Textstatus, Errorthrown) {
alert (Errorthrown);
}
});

Here is the method code for ASMX

The code is as follows Copy Code

[WebMethod]
public static string Getdemodata () {
Return ' [{' Demodata ': ' This is the JSON Data '}] ';
}

The way this is done is to treat the returned JSON data as a string, which is where the data is to be processed in an eval so that it becomes the true JSON object data.

Cases

Let's look at the HTML template first:

The code is as follows Copy Code
<table id= "Datas" border= "1" cellspacing= "0" style= "border-collapse:collapse" >


<tr>


<th>


Order id</th>


<th>


Customer id</th>


<th>


Employee id</th>


<th>


Order Date </th>


<th>


Shipping Date </th>


<th>


Shipper name </th>


<th>


Shipper's address </th>


<th>


Shippers City </th>


<th>


More Information </th>


</tr>


<tr id= "Template" >


<TD id= "OrderID" >


</td>


<TD id= "CustomerID" >


</td>


<TD id= "EmployeeID" >


</td>


<TD id= "OrderDate" >


</td>


<TD id= "ShippedDate" >


</td>


<TD id= "Shippedname" >


</td>


<TD id= "Shippedaddress" >


</td>


<TD id= "Shippedcity" >


</td>


<TD id= "More" >


</td>


</tr>


</table>


It must be noted that all the ID attributes inside, this is a key. Take a look at the code for AJAX requests and binding data.


The code is as follows Copy Code

$.ajax ({


Type: ' Get ',//Use the Get method to access the background


DataType: "JSON",//Return data in JSON format


URL: "Backhandler.ashx",//background address to access


Data: "pageindex=" + pageindex,//to send


Complete:function () {$ ("#load"). Hide ();},//ajax hidden loading prompt when the request completes


Success:function (msg) {//msg for returned data, do data binding here


var data = msg.table;


$.each (data, function (I, n) {


var row = $ ("#template"). Clone ();


Row.find ("#OrderID"). Text (n. Order ID);


Row.find ("#CustomerID"). Text (n. Customer ID);


Row.find ("#EmployeeID"). Text (n. Employee ID);


Row.find ("#OrderDate"). Text (ChangeDate (n. Order date));


if (n. Ship date!== undefined) row.find ("#ShippedDate"). Text (ChangeDate (n. Ship date));


Row.find ("#ShippedName"). Text (n. Shipper name);


Row.find ("#ShippedAddress"). Text (n. Shipper's address);


Row.find ("#ShippedCity"). Text (n. Shipper city);


Row.find ("#more"). HTML ("<a href=orderinfo.aspx?id=" + N. Order ID + "&pageindex=" +pageindex+ ">  More</a> ");


ROW.ATTR ("id", "Ready");//change the ID of the row that binds the data


Row.appendto ("#datas");//Add to Template's container


});

This is the jquery Ajax method, the return data is not complex, mainly explain how the data according to the definition of the template to the page. The first is this "var row = $ (" #template "). Clone ();" Copy the template first, then Row.find ("#OrderID"). Text (n. Order ID), which indicates that the Id=orderid tag is found, the innertext of it is set to the appropriate data, and, of course, it can be formatted as HTML data. Or you can use an external function to convert the data to the desired format, such as Row.find here ("#OrderDate"). Text (ChangeDate (n. Order date)); Some server controls feel like template binding data.
All of these are placed on a static page, only through the Ajax method to get the data from the background, all the HTML code is as follows:

The code is as follows Copy Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>test1</title>

<script language= "javascript" type= "Text/javascript" src= "Js/jquery-latest.pack.js" ></script>

<script language= "javascript" type= "Text/javascript" src= "Js/pagedate.js" ></script>

&lt;/head&gt;


&lt;body&gt;


&lt;div&gt;


&amp;nbsp;&lt;div&gt;


&lt;br/&gt;


&lt;input id= "The" "type=" button "value=" &lt;&lt; "/&gt;&lt;input id=" Previous "type=" button "


Value= "&lt;"/&gt;&lt;input id= "Next" type= "button" value= "&gt;"/&gt;&lt;input "Last" id= "button"


Value= "&gt;&gt;"/&gt;


&amp;nbsp;&lt;span id= "PageInfo" &gt;&lt;/span&gt;


&lt;table id= "Datas" border= "1" cellspacing= "0" style= "border-collapse:collapse" &gt;


&lt;tr&gt;


&lt;th&gt;


Order id&lt;/th&gt;


&lt;th&gt;


Customer id&lt;/th&gt;


&lt;th&gt;


Employee id&lt;/th&gt;


&lt;th&gt;


Order Date &lt;/th&gt;


&lt;th&gt;


Shipping Date &lt;/th&gt;


&lt;th&gt;


Shipper name &lt;/th&gt;


&lt;th&gt;


Shipper's address &lt;/th&gt;


&lt;th&gt;


Shippers City &lt;/th&gt;


&lt;th&gt;


More Information &lt;/th&gt;


&lt;/tr&gt;


&lt;tr id= "Template" &gt;


&LT;TD id= "OrderID" &gt;


&lt;/td&gt;


&LT;TD id= "CustomerID" &gt;


&lt;/td&gt;


&LT;TD id= "EmployeeID" &gt;


&lt;/td&gt;


&LT;TD id= "OrderDate" &gt;


&lt;/td&gt;


&LT;TD id= "ShippedDate" &gt;


&lt;/td&gt;


&LT;TD id= "Shippedname" &gt;


&lt;/td&gt;


&LT;TD id= "Shippedaddress" &gt;


&lt;/td&gt;


&LT;TD id= "Shippedcity" &gt;


&lt;/td&gt;


&LT;TD id= "More" &gt;


&lt;/td&gt;


&lt;/tr&gt;


&lt;/table&gt;


&lt;/div&gt;


&lt;div id= "Load" style= "left:0px; Position:absolute; top:0px; Background-color:red "&gt;


LOADING .....


&lt;/div&gt;


&lt;input type= "hidden" id= "PageCount"/&gt;


&lt;/div&gt;


&lt;/body&gt;


&lt;/html&gt;

Pagedata.js is to include the above Ajax request and binding data code JS, the entire page even the form does not need to do so what is the benefit. And look at one of the following templates

The code is as follows Copy Code
&lt;ul id= "Datas" &gt;


&lt;li id= "Template" &gt;


&lt;span id= "OrderID" &gt;


Fsdfasdf


&lt;/span&gt;


&lt;span id= "CustomerID" &gt;


&lt;/span&gt;


&lt;span id= "EmployeeID" &gt;


&lt;/span&gt;


&lt;span id= "OrderDate" &gt;


&lt;/span&gt;


&lt;span id= "ShippedDate" &gt;


&lt;/span&gt;


&lt;span id= "Shippedname" &gt;


&lt;/span&gt;


&lt;span id= "Shippedaddress" &gt;


&lt;/span&gt;


&lt;span id= "Shippedcity" &gt;


&lt;/span&gt;


&lt;span id= "More" &gt;


&lt;/span&gt;


&lt;/li&gt;


&lt;/ul&gt;


Still pay attention to the id attribute. You see here should understand, no matter what form of expression, as long as the id attribute the same, you can bind the data to the corresponding location. In this way, we do the program will not be modified by the artist to modify the code, and art also as long as the HTML can be done, do not need to make a template for server controls (but I have not encountered such art, are art design I have to change to the server control template).

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.