2013-05-13 92 views
1

我正在使用JQuery来调用我的WCF服务。响应正文显示我的JSON格式数据,但我不知道如何解析它。查看我的代码,了解到目前为止所做的工作。使用JQuery解析这个JSON

$.ajax({ 
      url: "http://wks52025:82/WcfDataService.svc/GetNotes()?$format=json", 
      type: "get", 
      datatype: "json", 
      success: function (data) { 
       $.each(data, function(i, item) { 
        alert(data[i].Title); 
       }) 
      } 
     }); 

    }); 

这是我的JSON

{ 
    "d": [ 
     { 
      "__metadata": { 
       "id": "http://wks52025:82/WcfDataService.svc/tblNotes(guid'93629a5f-2bb3-4190-b876-3d8a2997e76a')", 
       "uri": "http://wks52025:82/WcfDataService.svc/tblNotes(guid'93629a5f-2bb3-4190-b876-3d8a2997e76a')", 
       "type": "GenesisOnlineModel.tblNote" 
      }, 
      "NotesID": "93629a5f-2bb3-4190-b876-3d8a2997e76a", 
      "NotesTitle": "BSKYB", 
      "NotesText": "new Director of Brand and Media ", 
      "ParentID": 8879, 
      "ContactID": 309, 
      "JobID": 1000088150, 
      "UserID": "8b0e303a-68aa-49a5-af95-d994e2bdd5ac", 
      "GroupID": null, 
      "RelatedType": "Advertiser Contact", 
      "IsShared": true 
     }, 
     { 
      "__metadata": { 
       "id": "http://wks52025:82/WcfDataService.svc/tblNotes(guid'0f21866b-4a5c-417f-afe1-70ffbd1ce1f3')", 
       "uri": "http://wks52025:82/WcfDataService.svc/tblNotes(guid'0f21866b-4a5c-417f-afe1-70ffbd1ce1f3')", 
       "type": "GenesisOnlineModel.tblNote" 
      }, 
      "NotesID": "0f21866b-4a5c-417f-afe1-70ffbd1ce1f3", 
      "NotesTitle": "BSKYB More", 
      "NotesText": "Contacted all major contacts on this profile", 
      "ParentID": 8879, 
      "ContactID": null, 
      "JobID": null, 
      "UserID": "8b0e303a-68aa-49a5-af95-d994e2bdd5ac", 
      "GroupID": null, 
      "RelatedType": "Advertiser", 
      "IsShared": true 
     } 
    ] 
} 

在代码,我在我的警惕越来越不确定我成功的功能块。任何帮助都会很棒。

+0

尝试将整个'data'变量打印到控制台。一个想法是,由于关键“标题”不存在,这是问题而不是解析。 – 2013-05-13 13:51:16

+0

我使用Chrome的Web开发人员工具查看网络请求和响应。它返回一个JSON体。我也可以键入服务URL来查看JSON。 – 2013-05-13 13:52:41

回答

4

关闭!在你成功的块,请执行以下操作:

 success: function (data) { 
      $.each(data.d, function(i, item) { 
       alert(item.NotesTitle); 
      }) 
     } 

更新:实施@Johans评论。

+2

或只是'item.NotesTitle' – Johan 2013-05-13 13:50:36

+0

谢谢,现在更新:) – JAM 2013-05-13 13:51:24

+0

我upvoted这个,因为它也是正确的。 – 2013-05-13 13:55:54

2

您正在提醒alert(data[i].Title);。通过JSON的外观,JSON数组对象中的对象甚至都不具有Title属性,这就是为什么你得到undefined。我看到NotesTitle但没有Title。将其更改为:

success: function (data) { 
    $.each(data.d, function(i, item) { 
      alert(item.NotesTitle); 
    }) 
} 
+0

感谢这工作。将数据更改为data.d是我正在做的。我知道这是我小的东西:( – 2013-05-13 13:54:59

+0

我有,你的JQuery的实力太快了,所以:) – 2013-05-13 14:24:00