无法解析ASP.Net中从Server Side方法返回的JSON字符串

时间:2014-08-28 18:19:52

标签: javascript jquery asp.net json

我正在尝试解析这个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来解决这个问题,但没有成功。 请任何人......

1 个答案:

答案 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会获取每个数据属性的值。因此,例如,在某些时候,objdata.d。然后,您尝试提醒obj.titledata.d.title并且不存在。

通过迭代data.d,您可以将obj设置为data.d[0]。然后,

obj.title === data.d[0].title
          === "Yorkshire 199/8 * v Durham 237/10"`