JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于编程语言的文本格式存储和表示数据,基于 JavaScript 的对象字面量语法,由「键值对」和「数组」组成,是前后端数据交互的主流格式。JSON 文件中存储的是标准的 JSON 格式文本,数据由{}包裹对象、[]包裹数组,键名和字符串类型的值必须用双引号包裹,格式简洁且解析速度快。
在 jQuery 中,获取 JSON 格式数据有两种核心方式:原生封装的$.ajax()方法 和 JSON 专属快捷方法$.getJSON(),两种方式本质相通,核心优势是:当指定数据类型为 JSON 后,jQuery 会自动将后端返回的 JSON 格式字符串解析为 JavaScript 原生对象 / 数组,无需手动调用JSON.parse()或$.parseJSON(),可直接在回调函数中通过 .属性名 或 [索引] 调用数据,极大简化开发流程。
[
{"optionKey":"1", "optionValue":"Canon in D"},
{"optionKey":"2", "optionValue":"Wind Song"},
{"optionKey":"3", "optionValue":"Wings"}
]
HTML 代码
<div>点击按钮获取JSON数据</div>
<input type="button" id="button" value="确定" />
<div id="result"></div>
使用 Ajax 获取 JSON 数据
$(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;
});
});
简化版:使用 $.getJSON () 方法获取 JSON 文件
$(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 数据其实与其它 ajax 处理数据没什么很大的改动,我们只要简单处理一下 ajax 部份的 dataType 数据类型等于 json 即可解决了。
$("button").click(function(){
$.getJSON("demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
$.getJSON () 等价于完整的 Ajax 写法
$.ajax({
url: url,
data: data,
success: callback,
dataType: json
});
$.getJSON("test.js", function(json){
alert("JSON Data: " + json.users[3].name);
});
该写法适用于多层嵌套的 JSON 数据,json.users 表示获取 JSON 对象中的users数组,json.users[3] 表示数组的第四个元素,.name 表示获取该元素对象的name属性,是前端解析嵌套 JSON 的标准写法。
首先给出要传的 json 数据:[{"demoData":"This Is The JSON Data"}]
$.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();
$.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);
}
});
asmx 的方法代码
[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>
一定要注意的就是里面所有的 id 属性,这是模板绑定的核心:模板中每个数据展示节点的 id,与 JSON 数据中的字段名一一对应,通过克隆模板、赋值数据、追加到页面的方式,实现数据的批量渲染,是前端无刷新渲染列表的最优方案之一。
$.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");//添加到模板的容器中
});
<!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>
该开发模式的核心优点:前后端完全解耦、分工明确
正在加载... ...