Home > Web Front-end > JS Tutorial > body text

Detailed explanation of jQuery Ajax asynchronous processing of Json data

高洛峰
Release: 2017-01-12 09:42:57
Original
1072 people have browsed it

Let’s look at an official example first
Use AJAX request to obtain JSON data and output the result:

$("button").click(function(){
  $.getJSON("demo_ajax_json.js",function(result){
    $.each(result, function(i, field){
      $("div").append(field + " ");
    });
  });
});
Copy after login

This function is the abbreviation of Ajax function, which is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: callback,
  dataType: json
});
Copy after login

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-encoded before being appended to the URL.
The return data passed to callback can be a JavaScript object or an array defined in a JSON structure, and is parsed using the $.parseJSON() method.
Load JSON data from test.js and display a name field data in the JSON data:

$.getJSON("test.js", function(json){
  alert("JSON Data: " + json.users[3].name);
});
Copy after login

An asp.net instance
First give the json data to be transferred: [{"demoData ":"This Is The JSON Data"}]
1, use an ordinary aspx page to process it
I think this method is the easiest to process, look at the code below

$.ajax({ 
                                        type: "post", 
                                        url: "Default.aspx", 
                                        dataType: "json", 
                                        success: function (data) { 
                                                $("input#showTime").val(data[0].demoData); 
                                        }, 
                                        error: function (XMLHttpRequest, textStatus, errorThrown) { 
                                                alert(errorThrown); 
                                        } 
                                });
Copy after login

Here is the code for passing data in the background

Response.Clear(); 
Response.Write("[{"demoData":"This Is The JSON Data"}]"); 
Response.Flush(); 
Response.End();
Copy after login

This processing method directly parses the passed data into json data, which means that the front-end js code here may directly parse these data into json object data. Instead of string data, such as data[0].demoData, this json object data is used directly here
2, use webservice (asmx) to process
This processing method will not transfer the passed data Treated as json object data, but processed as a string, the following code

$.ajax({     
type: "post",     
url: "JqueryCSMethodForm.asmx/GetDemoData",     
dataType: "json",/*这句可用可不用,没有影响*/
contentType: "application/json; charset=utf-8",     
success: function (data) {     
$("input#showTime").val(eval('(' + data.d + ')')[0].demoData);
//这里有两种对数据的转换方式,两处理方式的效果一样//$("input#showTime").val(eval(data.d)[0].demoData);
},     
error: function (XMLHttpRequest, textStatus, errorThrown) {     
alert(errorThrown);     
}     
});
Copy after login

The following is the asmx method code

[WebMethod]     
public static string GetDemoData() {     
return "[{"demoData":"This Is The JSON Data"}]";     
}
Copy after login

This processing method here will pass back the json The data is processed as a string, so the data must be eval processed so that it can become a real json object data.
Let's take a look at the html template first:

  <table id="datas" border="1" cellspacing="0" style="border-collapse: collapse">
                <tr>
                    <th>
                        订单ID</th>
                    <th>
                        客户ID</th>
                    <th>
                        雇员ID</th>
                    <th>
                        订购日期</th>
                    <th>
                        发货日期</th>
                    <th>
                        货主名称</th>
                    <th>
                        货主地址</th>
                    <th>
                        货主城市</th>
                    <th>
                        更多信息</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>
Copy after login

Be sure to pay attention are all the id attributes inside, this is a key. Let's take a look at the code for AJAX request and data binding

    $.ajax({
            type: "get",//使用get方法访问后台
            dataType: "json",//返回json格式的数据
            url: "BackHandler.ashx",//要访问的后台地址
            data: "pageIndex=" + pageIndex,//要发送的数据
            complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(msg){//msg为返回的数据,在这里做数据绑定
                var data = msg.table;
                $.each(data, function(i, n){
                    var row = $("#template").clone();
                    row.find("#OrderID").text(n.订单ID);
                    row.find("#CustomerID").text(n.客户ID);
                    row.find("#EmployeeID").text(n.雇员ID);
                    row.find("#OrderDate").text(ChangeDate(n.订购日期));
                    if(n.发货日期!== undefined) row.find("#ShippedDate").text(ChangeDate(n.发货日期));
                    row.find("#ShippedName").text(n.货主名称);
                    row.find("#ShippedAddress").text(n.货主地址);
                    row.find("#ShippedCity").text(n.货主城市);
                    row.find("#more").html("<a href=OrderInfo.aspx?id=" + n.订单ID + "&pageindex="+pageIndex+"> More</a>");                    
                    row.attr("id","ready");//改变绑定好数据的行的id
                    row.appendTo("#datas");//添加到模板的容器中
                });
Copy after login

This is jQuery's AJAX method. The returned data is not complicated. It mainly explains how to display the data on the page according to the definition of the template. The first is this "var row = $("#template").clone();" first copy the template, and then row.find("#OrderID").text(n. order ID);, indicating that it is found For the tag with id=OrderID, set its innerText to the corresponding data. Of course, it can also be set to data in html format. Or convert the data into the required format through external functions, such as here row.find("#OrderDate").text(ChangeDate(n. order date)); It feels a bit like a server control doing template binding data.
All of these are placed in a static page, and data is only obtained from the background through the AJAX method. All html codes are as follows:




    test1
    
    


    

<table id="datas" border="1" cellspacing="0" style="border-collapse: collapse"> <tr> <th> 订单ID</th> <th> 客户ID</th> <th> 雇员ID</th> <th> 订购日期</th> <th> 发货日期</th> <th> 货主名称</th> <th> 货主地址</th> <th> 货主城市</th> <th> 更多信息</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>
LOADING....
Copy after login

PageData.js includes the above AJAX request and binding data The js of the code does not even use the form on the entire page. What are the benefits of doing so. Look at the following template

         <ul id="datas">
                <li id="template">
                    <span id="OrderID">
                        fsdfasdf
                    </span>
                    <span id="CustomerID">
                    </span>
                    <span id="EmployeeID">
                    </span>
                    <span id="OrderDate">
                    </span>
                    <span id="ShippedDate">
                    </span>
                    <span id="ShippedName">
                    </span>
                    <span id="ShippedAddress">
                    </span>
                    <span id="ShippedCity">
                    </span>
                    <span id="more">
                    </span>
                </li>
            </ul>
Copy after login


and still pay attention to the id attribute. Everyone should understand after seeing this that no matter what form of expression is used, as long as the id attribute is the same, the data can be bound to the corresponding location. In this case, those of us who are programmers will not modify the code due to the modification of the artist, and the artist only needs to make HTML, and there is no need to make templates for the server controls (but I have not encountered such an artist, They are all designed by the artist and I will change them into server control templates).

For more detailed explanations of jQuery Ajax asynchronous processing of Json data, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!