我正在尝试解析这个json数据
[
{ "title":"Yorkshire 199/8 * v Durham 237/10",
"link":"http://www.cricinfo.com/ci/engine/match/693421.html?CMP=OTC-RSS",
"description":"Yorkshire 199/8 * v Durham 237/10",
"guid":"http://www.cricinfo.com/ci/engine/match/693421.html"},
{
"title":"Essex v Warwickshire 271/7 *",
"link":"http://www.cricinfo.com/ci/engine/match/693423.html?CMP=OTC-RSS",
"description":"Essex v Warwickshire 271/7 *",
"guid":"http://www.cricinfo.com/ci/engine/match/693423.html"},
{
"title":"Singapore v Malaysia",
"link":"http://www.cricinfo.com/ci/engine/match/774365.html?CMP=OTC-RSS",
"description":"Singapore v Malaysia",
"guid":"http://www.cricinfo.com/ci/engine/match/774365.html"}
]
从服务器端方法返回并使用此方法迭代每个项目
$.ajax({
type: "POST",
url: "Default.aspx/ServerSideMethod",
//data: JSON.stringify({ 'p': 'Sent Text' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
//alert(data.d) //returns the result set displayed above.
$.each(data, function (i, obj) {
alert(obj.title); // returns undefined.
});
},
error: function (x, e) { alert(x.responseText); }
})
但它始终返回undefined。 我的jquery函数或数据有问题吗?我的服务器端功能正常工作,上面的Jquery函数也显示返回的值,但我无法解析这个值。
我也试过这个thread来解决这个问题,但没有成功。 请任何人......
答案 0 :(得分:0)
你正在迭代错误的对象:
$.ajax({
type: "POST",
url: "Default.aspx/ServerSideMethod",
//data: JSON.stringify({ 'p': 'Sent Text' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
//alert(data.d) //returns the result set displayed above.
$.each(data.d, function (i, obj) { // <---- use data.d here, not data
alert(obj.title);
});
},
error: function (x, e) { alert(x.responseText); }
})
当您只是迭代data
时,obj
会获取每个数据属性的值。因此,例如,在某些时候,obj
是data.d
。然后,您尝试提醒obj.title
,data.d.title
并且不存在。
通过迭代data.d
,您可以将obj
设置为data.d[0]
。然后,
obj.title === data.d[0].title
=== "Yorkshire 199/8 * v Durham 237/10"`