JSON(JavaScript Object Notation)是一種輕量級的數據交換格式。JSONM文件中包含了關于“名稱”和“值”的信息。有時候我們需要讀取JSON格式的數據文件,在jQuery中可以使用Ajax或者 $.getJSON()方法實現。
下面就使用jQuery讀取music.txt文件中的JSON數據格式信息。
首先,music.txt中的內容如下:
[
{"optionKey":"1", "optionValue":"Canon in D"},
{"optionKey":"2", "optionValue":"Wind Song"},
{"optionKey":"3", "optionValue":"Wings"}
]
<div>點擊按鈕獲取JSON數據</div>
<input type="button" id="button" value="確定" />
<div id="result"></div>
$(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;
});
});
$(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數據詳解
jquery ajax處理json數據其實與其它ajax處理數據沒什么很大的改動,我們只要簡單處理一下ajax部份的dataType數據類型等于json即可解決了。
使用 AJAX 請求來獲得 JSON 數據,并輸出結果:
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
$.ajax({
url: url,
data: data,
success: callback,
dataType: json
});
$.getJSON("test.js", function(json){
alert("JSON Data: " + json.users[3].name);
});
$.ajax({
type: "post",
url: "Default.aspx",
dataType: "json",
success: function (data) {
$("input#showTime").val(data[0].demoData);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
Response.Clear();
Response.Write("[{"demoData":"This Is The JSON Data"}]");
Response.Flush();
Response.End();
2,使用webservice(asmx)來處理
這種處理方式就不會將傳遞過來的數據當成是json對象數據,而是作為字符串來處理的,
$.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);
}
});
[WebMethod]
public static string GetDemoData() {
return "[{"demoData":"This Is The JSON Data"}]";
}
<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>
$.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");//添加到模板的容器中
});
這個是jQuery的AJAX方法,返回數據并不復雜,主要說明一下怎么把數據按模板的定義顯示到到頁面上。首先是這個“var row = $("#template").clone();”先把模板復制一份,接下來row.find("#OrderID").text(n.訂單ID);,表示找到id=OrderID的標記,設置它的innerText為相應的數據,當然也可以設置為html格式的數據。或者是通過外部的函數把數據轉換成需要的格式,比如這里row.find("#OrderDate").text(ChangeDate(n.訂購日期));有點服務器控件做模板綁定數據的感覺。<!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>
<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>