Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery uses Ajax to get sample code for JSON format data


May 08, 2021 JSON


Table of contents


JavaScript Object Notation is a lightweight data exchange format. T he JSONM file contains information about "name" and "value". S ometimes we need to read data files in JSON format, which can be implemented using the Ajax or $.getJSON() method in jQuery.

Here's how to use jQuery to .txt the JSON data format information in the music file.
First, the contents .txt music are as follows:

The code is as follows:
[ 
{"optionKey":"1", "optionValue":"Canon in D"}, 
{"optionKey":"2", "optionValue":"Wind Song"}, 
{"optionKey":"3", "optionValue":"Wings"} 
] 

Down is the HTML code:

The code is as follows:
<div>点击按钮获取JSON数据</div> 
<input type="button" id="button" value="确定" /> 
<div id="result"></div> 

Use Ajax to get JSON data:

The code is as follows:
$(document).ready(function(){ 
$('#button').click(function(){ 
$.ajax({ 
type:"GET", 
url:"music.txt", 
dataType:"json", 
success:function(data){ 
var music="<ul>"; 
//i表示在data中的索引位置,n表示包含的信息的对象 
$.each(data,function(i,n){ 
//获取对象中属性为optionsValue的值 
music+="<li>"+n["optionValue"]+"</li>"; 
}); 
music+="</ul>"; 
$('#result').append(music); 
} 
}); 
return false; 
}); 
}); 

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

The code is as follows:
$(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 asynchronously processes the Johnson data in detail

jquery ajax processing jason data is not much different from other ajax processing data, we just need to simply deal with the ajax part of the dataty type data is equal to jason can be solved.
Use AJAX requests to obtain JSON data and output the results:

The code is as follows:
$("button").click(function(){
  $.getJSON("demo_ajax_json.js",function(result){
    $.each(result, function(i, field){
      $("div").append(field + " ");
    });
  });
});

The function is a short Ajax function, equivalent to:

The code is as follows:
$.ajax({
  url: url,
  data: data,
  success: callback,
  dataType: json
});

The data sent to the server can be attached 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 encoded by the URL before it is attached to the URL.

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

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

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

An instance of asp.net system

First give the json data to pass on: "demoData": "This Is The JSON Data"

1, the use of ordinary aspx page to deal with

I think this way to deal with is the simplest, look at the following code.

The code is as follows:
$.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

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

This processing parses the passed data directly into jason data, which means that the foreside js code here may parse the data directly into jason object data, not string data, such as data. demoData, where the jason object data is used directly

2. Use webservice (asmx) to handle it
This processing does not treat the passed data as jason object data, but as a string.

The code is as follows:
$.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);     
}     
});

Here's the method code for asmx

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

This processing here treats the passed jason data as a string, so that the data can be processed in order to become the real johnson object data.

Let's take a look at the html template first:

The code is as follows:
<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>

It is important to note that all the id properties are inside, and this is a key. Let's take a look at the code for AJAX requests and binding data

The code is as follows:
$.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");//添加到模板的容器中
                });

This is jQuery's AJAX method, which returns data that is not complicated and mainly explains how to display the data on the page as defined by the template. T he first is this "var row - $" ("#template"). " Copy the template first, then row.find ("#OrderID"). text (n. order ID); , indicates that the tag of the id-OrderID is found, that its innerText is set as the corresponding data, and that the data can of course be set to html format. O r convert the data into the format you want through external functions, such as here row.find ("#OrderDate"). text (changeDate (n. order date)); A bit of a server control does template binding data feeling.


All of these are placed on a static page, data is obtained from the background only through the AJAX method, and all html code is as follows:

The code is 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>
         <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="  >>  " />
             <span id="pageinfo"></span>
            <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>
        </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 to include the above AJAX request and binding data code js, the entire page does not even use the form, what good is it? Look at the following template

The code is as follows:
<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> 

You should also pay attention to the id property. Y ou should see here that no matter what form of representation, as long as the id properties are the same, you can bind the data to the corresponding location. In this way, those of us who do the program will not be because of the modification of the art and modify the code, and the art also as long as the html can be made, do not need to do a template for the server control.