jQuery中使用Ajax獲取JSON格式數(shù)據(jù)示例代碼

2022-05-17 14:43 更新

JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式。JSONM文件中包含了關(guān)于“名稱”和“值”的信息。有時(shí)候我們需要讀取JSON格式的數(shù)據(jù)文件,在jQuery中可以使用Ajax或者$.getJSON()方法實(shí)現(xiàn)。 

下面就使用jQuery讀取music.txt文件中的JSON數(shù)據(jù)格式信息。 
首先,music.txt中的內(nèi)容如下: 

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

下來(lái)是HTML代碼:

代碼如下:
<div>點(diǎn)擊按鈕獲取JSON數(shù)據(jù)</div> 
<input type="button" id="button" value="確定" /> 
<div id="result"></div> 

使用Ajax獲取JSON數(shù)據(jù):

代碼如下:
$(document).ready(function(){ 
$('#button').click(function(){ 
$.ajax({ 
type:"GET", 
url:"music.txt", 
dataType:"json", 
success:function(data){ 
var music="<ul>"; 
//i表示在data中的索引位置,n表示包含的信息的對(duì)象 
$.each(data,function(i,n){ 
//獲取對(duì)象中屬性為optionsValue的值 
music+="<li>"+n["optionValue"]+"</li>"; 
}); 
music+="</ul>"; 
$('#result').append(music); 
} 
}); 
return false; 
}); 
}); 

當(dāng)然,也可以使用$.getJSON()方法,代碼簡(jiǎn)潔一點(diǎn):

代碼如下:
$(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數(shù)據(jù)詳解

jquery ajax處理json數(shù)據(jù)其實(shí)與其它ajax處理數(shù)據(jù)沒(méi)什么很大的改動(dòng),我們只要簡(jiǎn)單處理一下ajax部份的dataType數(shù)據(jù)類型等于json即可解決了。
使用 AJAX 請(qǐng)求來(lái)獲得 JSON 數(shù)據(jù),并輸出結(jié)果:

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

該函數(shù)是簡(jiǎn)寫(xiě)的 Ajax 函數(shù),等價(jià)于:

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

發(fā)送到服務(wù)器的數(shù)據(jù)可作為查詢字符串附加到 URL 之后。如果 data 參數(shù)的值是對(duì)象(映射),那么在附加到 URL 之前將轉(zhuǎn)換為字符串,并進(jìn)行 URL 編碼。

傳遞給 callback 的返回?cái)?shù)據(jù),可以是 JavaScript 對(duì)象,或以 JSON 結(jié)構(gòu)定義的數(shù)組,并使用 $.parseJSON() 方法進(jìn)行解析。

從 test.js 載入 JSON 數(shù)據(jù)并顯示 JSON 數(shù)據(jù)中一個(gè) name 字段數(shù)據(jù):

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

一個(gè)與asp.net實(shí)例

首先給出要傳的json數(shù)據(jù):[{"demoData":"This Is The JSON Data"}]

1、使用普通的aspx頁(yè)面來(lái)處理

本人覺(jué)得這種方式處理起來(lái)是最簡(jiǎn)單的了,看下面的代碼吧。

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

這里是后臺(tái)傳遞數(shù)據(jù)的代碼

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

這種處理的方式將傳遞過(guò)來(lái)的數(shù)據(jù)直接解析為json數(shù)據(jù),也就是說(shuō)這里的前臺(tái)js代碼可能直接把這些數(shù)據(jù)解析成json對(duì)象數(shù)據(jù),而并非字符串?dāng)?shù)據(jù),如data[0].demoData,這里就直接使用了這個(gè)json對(duì)象數(shù)據(jù)

2、使用webservice(asmx)來(lái)處理
這種處理方式就不會(huì)將傳遞過(guò)來(lái)的數(shù)據(jù)當(dāng)成是json對(duì)象數(shù)據(jù),而是作為字符串來(lái)處理的,

代碼如下:
$.ajax({     
type: "post",     
url: "JqueryCSMethodForm.asmx/GetDemoData",     
dataType: "json",/*這句可用可不用,沒(méi)有影響*/
contentType: "application/json; charset=utf-8",     
success: function (data) {     
$("input#showTime").val(eval('(' + data.d + ')')[0].demoData);
//這里有兩種對(duì)數(shù)據(jù)的轉(zhuǎn)換方式,兩處理方式的效果一樣//$("input#showTime").val(eval(data.d)[0].demoData);
},     
error: function (XMLHttpRequest, textStatus, errorThrown) {     
alert(errorThrown);     
}     
});

下面為asmx的方法代碼

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

這里的這種處理方式就把傳遞回來(lái)的json數(shù)據(jù)當(dāng)成了字符串來(lái)處理的,所在就要對(duì)這個(gè)數(shù)據(jù)進(jìn)行eval的處理,這樣才能成為真正的json對(duì)象數(shù)據(jù),

我們先來(lái)看一下html模板: 

代碼如下:
<table id="datas" border="1" cellspacing="0" style="border-collapse: collapse">
    <tr>
        <th>訂單ID</th>
        <th>客戶ID</th>
        <th>雇員ID</th>
        <th>訂購(gòu)日期</th>
        <th>發(fā)貨日期</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>

 一定要注意的就是里面所有的id屬性,這個(gè)是一個(gè)關(guān)鍵。再來(lái)看一下AJAX請(qǐng)求和綁定數(shù)據(jù)的代碼

代碼如下:
$.ajax({
            type: "get",//使用get方法訪問(wèn)后臺(tái)
            dataType: "json",//返回json格式的數(shù)據(jù)
            url: "BackHandler.ashx",//要訪問(wèn)的后臺(tái)地址
            data: "pageIndex=" + pageIndex,//要發(fā)送的數(shù)據(jù)
            complete :function(){$("#load").hide();},//AJAX請(qǐng)求完成時(shí)隱藏loading提示
            success: function(msg){//msg為返回的數(shù)據(jù),在這里做數(shù)據(jù)綁定
                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.訂購(gòu)日期));
                    if(n.發(fā)貨日期!== undefined) row.find("#ShippedDate").text(ChangeDate(n.發(fā)貨日期));
                    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");//改變綁定好數(shù)據(jù)的行的id
                    row.appendTo("#datas");//添加到模板的容器中
                });

這個(gè)是jQuery的AJAX方法,返回?cái)?shù)據(jù)并不復(fù)雜,主要說(shuō)明一下怎么把數(shù)據(jù)按模板的定義顯示到到頁(yè)面上。首先是這個(gè)“var row = $("#template").clone();”先把模板復(fù)制一份,接下來(lái)row.find("#OrderID").text(n.訂單ID);,表示找到id=OrderID的標(biāo)記,設(shè)置它的innerText為相應(yīng)的數(shù)據(jù),當(dāng)然也可以設(shè)置為html格式的數(shù)據(jù)。或者是通過(guò)外部的函數(shù)把數(shù)據(jù)轉(zhuǎn)換成需要的格式,比如這里row.find("#OrderDate").text(ChangeDate(n.訂購(gòu)日期));有點(diǎn)服務(wù)器控件做模板綁定數(shù)據(jù)的感覺(jué)。


所有的這些,都是放在一個(gè)靜態(tài)的頁(yè)面里,只通過(guò)AJAX方法從后臺(tái)獲取數(shù)據(jù),所有html代碼如下:

代碼如下:
<!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>
                        訂購(gòu)日期</th>
                    <th>
                        發(fā)貨日期</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就是包括上面AJAX請(qǐng)求和綁定數(shù)據(jù)代碼的js,整個(gè)頁(yè)面連form都不用,這樣做有什么好處呢。再看下面一個(gè)模板

代碼如下:        
<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> 

還是要注意id屬性。大家看到這里應(yīng)該明白了,不管用什么樣的表現(xiàn)形式,只要id屬性相同,就可以把數(shù)據(jù)綁定到對(duì)應(yīng)的位置。這樣的話,我們這些做程序的就不會(huì)因?yàn)槊拦さ男薷亩薷拇a了,而且美工也只要做出html就可以了,不需要為服務(wù)器控件做模板。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)