jQuery using Ajax JSON format data acquired Sample Code

JSON (JavaScript Object Notation) is a lightweight data interchange format. JSONM file contains information about the "name" and "value". Sometimes we need to read the data file in JSON format, you can use Ajax or $ .getJSON in jQuery () methods. 

Here use jQuery JSON data format information read music.txt file. 

First, the content music.txt as follows: 

code show as below:

[ 
{"optionKey":"1", "optionValue":"Canon in D"}, 
{"optionKey":"2", "optionValue":"Wind Song"}, 
{"optionKey":"3", "optionValue":"Wings"} 
] 

 

Down is the HTML code:

code show as below:

<div> Click the button to get the JSON data </ div> 
<the INPUT of the type = "the Button" the above mentioned id = "the Button" value = "OK" /> 
<div the above mentioned id = "the Result"> </ div>

 Use Ajax get JSON data:

code show as below:

$ (the Document) .ready (function () { 
. $ ( '# the Button') the Click (function () { 
$ .ajax ({ 
of the type: "GET", 
url: "music.txt", 
dataType: "json", 
Success: function (data) { 
var = Music "<UL>"; 
// I index represents the position of data, n is the object contains information indicating 
$ .each (data, function (I, n) { 
// Get object attribute optionsValue value 
Music + = "<Li>" + n-[ "the optionValue"] + "</ Li>"; 
}); 
Music + = "</ UL>"; 
$ ( '# Result') the append. (Music); 
} 
}); 
return to false; 
}); 
});

 

Of course, you can also use the $ .getJSON () method, the code simple thing:

code show as below:

$(document).ready(function(){ 
$('#button').click(function(){ 
$.getJSON('music.txt',function(data){ 
var music="<ul>"; 
$.each(data,function(i,n){ 
music+="<li>"+n["optionValue"]+"</li>"; 
}); 
music+="</ul>"; 
$('#result').append(music); 
}); 
return false; 
}); 
}); 

 

jQuery Ajax Json data Detailed asynchronous processing

jquery ajax json data processing actually process the data with other ajax no big changes, we simply deal with what most of ajax dataType data type is equal to json resolved.

JSON using AJAX request to obtain data, and outputs the result:

code show as below:

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

 

This function is abbreviated Ajax functions, is equivalent to:

code show as below:

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

 

Data may be sent to the server as to append after the URL. If the value of the parameter is a data object (map), then prior to the URL converted to a string, and the URL encoded.

Back passed to the callback data, the object can be a JavaScript, or JSON an array structure definition and use $ .parseJSON () method resolution.

Loading data from JSON test.js JSON data and display data in a name field:

code show as below:

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

 

One example of asp.net

Firstly, to pass json data: { "demoData": "This Is The JSON Data"}

1, using ordinary aspx page to handle

I feel this way is the easiest to deal with them, look at the code below it.

code show as 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); 
          } 
      });

 

Here is the code of the background data transfer

code show as below:

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

 

Data treated in this manner is passed over directly to parse json data, that is to say where the front js code may be parsed into data directly to the target data json, rather than the string data, such as data0.demoData, here used directly this json object data

2, using webservice (asmx) treated

This approach would not be the data transferred over json object data as is, but is handled as a string,

code show as below:

.ajax $ ({      
type: "POST",      
URL: "JqueryCSMethodForm.asmx / GetDemoData",      
dataType: "JSON", / * phrase may or may not, have no effect * / 
contentType: "file application / JSON; charset = UTF- . 8 ",      
Success: function (data) {      
. $ (" the showTime INPUT # ") Val (the eval ( '(' + data.d + ')') [0] .demoData); 
// there are two data conversion method, the same effect of the two treatments //$("input#showTime").val(eval(data.d)[0].demoData); 
},      
error: function (the XMLHttpRequest, textStatus, errorThrown) {      
Alert (errorThrown);      
}      
});

 

The following code is a method asmx

code show as below:

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

 

This approach here is to put back pass json data as a string processing, where it is necessary for the data processing eval, so as to become a true json object data,

We first look at the html template: 

code show as below:

<Table ID = "DATAS" border = ". 1" cellspacing = "0" style = "border-Collapse: Collapse"> 
    <TR> 
        <TH> Order ID </ TH> 
        <TH> Client ID </ TH> 
        <TH > employee ID </ TH> 
        <TH> Order date </ TH> 
        <TH> delivery date </ TH> 
        <TH> ShipName </ TH> 
        <TH> owner address </ TH> 
        <TH> shippers city < / TH> 
        <TH> more information </ TH> 
   </ TR> 
   <TR ID = "Template"> 
       <TD ID = "the OrderID"> </ TD> 
       <TD ID = "the 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>

 Be sure to pay attention to is inside all of the id attribute, this is a key. Let's look at the code AJAX requests and binding data

code show as below:

.ajax $ ({ 
            of the type: "get", // Use get backstage access method 
            dataType: "json", // return json formatted data 
            url: "BackHandler.ashx", // address to access back-end 
            data: "pageIndex = "+ pageIndex, // the data to be transmitted 
            : {. complete function () $ (" # load ") hide ();} Hide loading prompted, // AJAX request is complete 
            success: function (msg) {// msg for the returned data, binding data do 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 (the n-customer ID);. 
                    row.find ( "# EmployeeID") text (the n-employee ID)..;
                    row.find ( "# OrderDate") text (ChangeDate (n order date).);.
                    if (.! n delivery date == undefined) row.find ( "# ShippedDate ") text (ChangeDate (n date of shipment).);. 
                    .. row.find ( "# ShippedName") text (the n-ShipName ); 
                    row.find ( "# ShippedAddress") text (the n-owner address);.. 
                    . row.find ( "# ShippedCity") text (the n-owner of the city);. 
                    . row.find ( "# More") HTML ( "<a href=OrderInfo.aspx?id=" + n.订单ID "&pageindex="+pageIndex+"> More </a> +");                     
                    row.attr ( "ID", "READY"); // change binding good data id line 
                    row.appendTo ( "# datas"); // add to a container template 
                });

 

This is a jQuery AJAX method, the return data is not complicated, mainly to explain how the data is displayed according to the custom template onto the page. The first is the "var row = $ (" # template ") clone ();.". First copy of the template, the next row.find ( "# OrderID") text (. N order ID) ;, expressed found id = OrderID tag, set its corresponding data innerText, of course, also be provided to the data in html format. Or by an external function to convert data into the required format, such as here row.find ( "# OrderDate") text (ChangeDate (n order date).);. A bit server controls do feel bound data template.

All of these are placed in a static page, only to get data from the background via AJAX method, all html code is as follows:

code show as below:

<!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>
         <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 ">>" /> 
                    <TH>
             <span id="pageinfo"></span>
            <Table ID = "DATAS" border = ". 1" cellspacing = "0" style = "border-Collapse: Collapse"> 
                <TR> 
                    <TH> 
                        Order ID </ TH> 
                    <TH> 
                        Client ID </ TH> 
                    <TH > 
                        employee ID </ th> 
                    <TH> 
                        Order date </ th> 
                    <TH> 
                        delivery date </ th> 
                    <TH> 
                        ShipName </ th> 
                    <TH> 
                        owner address </ th>
                        City owner </ 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>
        </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 included js above AJAX requests and data binding code, the entire page do not even form, what good is it to do so. Look below a template

code show as below:

<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> 

 Or pay attention to the id attribute . We see here should understand that, no matter what kind of manifestations with, as long as the same id attribute, you can bind data to the corresponding position. In this case, we do these programs will not be modified because the art of modifying code, and artists also make html as long as you can, do not need a template for the server control.

Guess you like

Origin www.cnblogs.com/l9l99/p/11789436.html