试图循环Json

时间:2012-03-09 20:54:43

标签: jquery json

$('#myClick2').change(function () {
   if (this.checked) {
     $.getJSON('message_center_getMessageLists.asp', {}, function (json) {

             $.each(json.items, function (i, item) {
              alert(item.rank.distID);
              alert(item.rank.name);
              alert(item.rank.description);
             });
         })
         .error(function () {
           alert("There was an error while trying to make this request;  If it persists please contact support"); 
   });
  }
});

我似乎无法完成上述工作,我不得不遗漏一些东西。

以下是我试图循环的Json

{
    "rank": [
        {
            "distID": "1",
            "name": "John Doe",
            "description": "My Rank"
        },
        {
            "distID": "2",
            "name": "Jane Dow",
            "description": "My Rank"
        },
        {
            "distID": "3",
            "name": "Robin Doe",
            "description": "My Rank"
        },
        {
            "distID": "4",
            "name": "Ryan Doe",
            "description": "My Rank"
        }
    ]
}

3 个答案:

答案 0 :(得分:3)

看起来你可能想要:

  

$。each(json.rank,function(i,item)

答案 1 :(得分:2)

如果这是你的JSON回复,你需要这个:

$.each(json.rank, function (i, item) {
    alert(item.distID);
    alert(item.name);
    alert(item.description);
});

这是因为您的JSON是一个具有一个名为rank的属性的对象,该属性包含您想要迭代的对象数组。因此,您将json.rank传递给$.each(),您将获得数组中的每个对象item

添加一些换行符以便您可以更好地看到它,这是您的JSON响应:

{
    "rank": [
        {"distID":"1","name":"John Doe","description":"My Rank"},
        {"distID":"2","name":"Jane Dow","description":"My Rank"},
        {"distID":"3","name":"Robin Doe","description":"My Rank"},
        {"distID":"4","name":"Ryan Doe","description":"My Rank"}
    ]
}

因此,如果将其设置为等于您的成功参数json,则可以看到该数组将如何json.rank。然后,您可以使用.each()item.distId等访问item.description循环中的每个项目属性...

答案 2 :(得分:-1)

好吧,item.rank没有任何意义。 rank的值是JSON对象的数组。你真正想要的是循环排名的元素。这种语法将是iffy但

$.each(json.items.rank (i, item) {
  alert(distId);
});