准备工作
·customer类
复制代码 代码如下:
public class customer
{
public int unid { get; set; }
public string customername { get; set; }
public string memo { get; set; }
public string other { get; set; }
}
·服务端处理(json_1.ashx)
复制代码 代码如下:
customer customer = new customer
{ unid=1,customername=宋江,memo=天魁星,other=黑三郎};
string strjson = newtonsoft.json.jsonconvert.serializeobject(customer);context.response.write(strjson);
(一)jquery. getjson方法定义:jquery.getjson( url, data, callback )
通过get请求得到json数据
·url用于提供json数据的地址页
·data(optional)用于传送到服务器的键值对
·callback(optional)回调函数,json数据请求成功后的处理函数
复制代码 代码如下:
function(data, textstatus) {
// data是一个json对象
// textstatus will be success
this; // the options for this ajax request
}
(1)一个对象
复制代码 代码如下:
$.getjson(
webdata/json_1.ashx,
function(data) {
$(#divmessage).text(data.customername);
}
);
向json_1.ashx地址请求json数据,接收到数据后,在function中处理data数据。 这里的data的数据是一条记录,对应于一个customer实例,其中的数据以k/v形式存在。即以[object,object]数组形式存在。
{unid:1,customername:宋江,memo:天魁星,other:黑三郎}所以在访问时,以data.property来访问,下面以k/v循环来打印这条宋江的记录:
复制代码 代码如下:
$.getjson(
webdata/json_1.ashx,
function(data) {
var tt=;
$.each(data, function(k, v) {
tt += k + : + v +
;
})
$(#divmessage).html(tt);
});
结果:
unid:1
customername:宋江
memo:天魁星
other:黑三郎(2)对象数组
ashx文件(json_1.ashx)修改:
复制代码 代码如下:
list _list = new list();
customer customer = new customer
{ unid=1,customername=宋江,memo=天魁星,other=黑三郎};
customer customer2 = new customer
{ unid = 2, customername = 吴用, memo = 天机星, other = 智多星 };_list.add(customer);
_list.add(customer2);
string strjson = newtonsoft.json.jsonconvert.serializeobject(_list);
它生成的json对象的字符串是:[{unid:1,customername:宋江,memo:天魁星,other:黑三郎},
{unid:2,customername:吴用,memo:天机星,other:智多星}]
这里可以看到做为集合的json对象不是再一条记录,而是2条记录,是一个[[object,object]]数组:[object,object][object,object],而每个[object,object]表示一条记录,对应一个customer,其实也是k/v的形式,而这个v就是一个customer对象,而这个k是从0开始的索引。
复制代码 代码如下:
$.getjson(
webdata/json_1.ashx,
function(data) {
$.each(data, function(k, v) {
alert(k);
});
});
这时,k值为0,1……列表json对象的方法:
复制代码 代码如下:
$.getjson(
webdata/json_1.ashx,
function(data) {
var tt = ;
$.each(data, function(k, v) {
$.each(v,function(kk, vv) {
tt += kk + : + vv +
;
});
});
$(#divmessage).html(tt);
});
结果:
unid:1
customername:宋江
memo:天魁星
other:黑三郎
unid:2
customername:吴用
memo:天机星
other:智多星
这里用了嵌套循环,第一个循环用于从list中遍历customer对象,第二个循环用于从customer对象中遍历customer对象的属性,也就是k/v对。