JQuery Ajax handles Json data asynchronously

  • 2020-03-26 23:00:58
  • OfStack

Let's start with an official example
Use the AJAX request to get the JSON data and output the results:

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

This function is a simplified Ajax function, equivalent to:

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

The 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 returned data passed to the callback can be a JavaScript object or an array defined in a JSON structure and parsed using the $.parsejson () method.
Load the JSON data from test.js and display the name field data in the JSON data:

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

An instance with asp.net
[{"demoData":"This Is The json Data"}]
1. Use normal aspx pages for processing
I think this approach is the easiest to handle, see the following 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); 
                                        } 
                                });

Here is the code that passes the data in the background

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

This process directly parses the passed data into json data, which means that the foreground js code here might parse the data directly into json object data instead of string data, such as data[0].demodata, which is directly used here
2, use webservice(asmx) to handle
Instead of treating the data passed in as json object data, it is treated as a string, as shown in 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);
// There are two ways to transform the data, both of which have the same effect //$("input#showTime").val(eval(data.d)[0].demoData);
},     
error: function (XMLHttpRequest, textStatus, errorThrown) {     
alert(errorThrown);     
}     
});

Here is the method code for asmx

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

So what we're going to do here is we're going to treat the returned json data as a string, and we're going to have to eval this data to make it a true 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>
                         The order ID</th>
                    <th>
                         The customer ID</th>
                    <th>
                         employees ID</th>
                    <th>
                         Order date </th>
                    <th>
                         The delivery date </th>
                    <th>
                         The shipper name </th>
                    <th>
                         The shipper address </th>
                    <th>
                         The shipper city </th>
                    <th>
                         For 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's important to note that all of the id attributes are in there, and that's a key. Take a look at the code for AJAX requests and binding data

    $.ajax({
            type: "get",//Use the get method to access the background
            dataType: "json",//Returns data in json format
            url: "BackHandler.ashx",//The background address to be accessed
            data: "pageIndex=" + pageIndex,//The data to be sent
            complete :function(){$("#load").hide();},//Hide the loading prompt when the AJAX request completes
            success: function(msg){//MSG does the data binding here for the returned data
                var data = msg.table;
                $.each(data, function(i, n){
                    var row = $("#template").clone();
                    row.find("#OrderID").text(n. The order ID);
                    row.find("#CustomerID").text(n. The customer ID);
                    row.find("#EmployeeID").text(n. employees ID);
                    row.find("#OrderDate").text(ChangeDate(n. Order date ));
                    if(n. The delivery date !== undefined) row.find("#ShippedDate").text(ChangeDate(n. The delivery date ));
                    row.find("#ShippedName").text(n. The shipper name );
                    row.find("#ShippedAddress").text(n. The shipper address );
                    row.find("#ShippedCity").text(n. The shipper city );
                    row.find("#more").html("<a href=OrderInfo.aspx?id=" + n. The order ID + "&pageindex="+pageIndex+">&nbsp;More</a>");                    
                    row.attr("id","ready");//Change the id of the row where the data is bound
                    row.appendTo("#datas");//Add to the container of the template
                });

This is the AJAX method of jQuery, return data is not complex, mainly explain how to display the data according to the definition of the template to the page. The first is the "var row = $("#template").clone();" Make a copy of the template, then row.find("#OrderID").text(n. OrderID); , to find the tag with id=OrderID, and set its innerText to the corresponding data, or HTML data. Or an external function that converts the data to the desired format, such as row.find("#OrderDate").text(ChangeDate(n. OrderDate)); A bit of a server control to do template binding data.
All of these are put in a static page, only through AJAX methods to get data from the background, all the HTML code as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <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>
</head>
<body>
    <div>
        &nbsp;<div>
            <br />
            <input id="first" type="button" value="  <<  " /><input id="previous" type="button"
                value="  <  " /><input id="next" type="button" value="  >  " /><input id="last" type="button"
                    value="  >>  " />
            &nbsp;<span id="pageinfo"></span>
            <table id="datas" border="1" cellspacing="0" style="border-collapse: collapse">
                <tr>
                    <th>
                         The order ID</th>
                    <th>
                         The customer ID</th>
                    <th>
                         employees ID</th>
                    <th>
                         Order date </th>
                    <th>
                         The delivery date </th>
                    <th>
                         The shipper name </th>
                    <th>
                         The shipper address </th>
                    <th>
                         The shipper city </th>
                    <th>
                         For 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>
        </div>
        <div id="load" style="left: 0px; position: absolute; top: 0px; background-color: red">
            LOADING....
        </div>
        <input type="hidden" id="pagecount" />
    </div>
</body>
</html>

Pagedata.js is the js that includes the above AJAX requests and the data binding code, and the entire page doesn't even use the form. Look at the next 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> 

Also notice the id attribute. And you can see here that no matter what the representation is, as long as the id property is the same, you can bind the data to the corresponding location. In this way, those of us who do the program will not modify the code because of the artist's modification, and the artist also as long as the HTML can be made, do not need to make a template for the server control (although I have not met such an artist, is the artist designed me to change the server control template).

Related articles: