无法解析JSON字符串从服务器端方法返回在ASP.Net
问题描述:
我试图解析此JSON数据无法解析JSON字符串从服务器端方法返回在ASP.Net
[
{ "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来解决这个问题,但没有成功。 任何一个请...
答
你迭代错了对象:
$.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"`
'console.log(data);'它是你所期望的吗? – epascarello 2014-08-28 18:21:43
我需要在我的网页上显示全部三个项目。这就是为什么我想获得obj.title,obj.description等...... – Lali 2014-08-28 18:23:50
@liaqatali没关系。 'console.log(data)'显示了什么? – 2014-08-28 18:27:48