2012-10-08 46 views
1

這是我在Jsonlint驗證的本地Json。爲什麼我的jquery json each()循環返回undefined?

{ 
"messages": { 
    "count": "0", 
    "items": [ 
     { 
      "MessageID": "1", 
      "Starred": 0, 
      "BodyPrev": "You wouldn't believe what has just happenedYou wouldn't believe what has ", 
      "FromUserID": "1", 
      "FromName": "Daisy Purdye", 
      "FromUN": "daisypurdye", 
      "Subject": "Yeayeah", 
      "Body": "You wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happenedYou wouldn't believe what has just happened", 
      "Ctime": "10/4/2012", 
      "isRead": "1" 
     }, 
     { 
      "MessageID": "2", 
      "Starred": 1, 
      "BodyPrev": "Whatever", 
      "FromUserID": "1", 
      "FromName": "Daisy Purdye", 
      "FromUN": "daisypurdye", 
      "Subject": "Not true mate", 
      "Body": "Whatever", 
      "Ctime": "5/3/2012", 
      "isRead": "1" 
     } 
    ] 
} 

}

,這裏是jQuery的打印出來的消息...

<script> 
    $.getJSON("/json/messages.json",function(result){ 
     $.each(result, function(i, messages){ 
      console.log(messages.items.Subject) 
     }); 
     }); 
    </script> 

它只是返回undefined。

回答

4

$.each應該接收到一個數組,並將其傳遞給不是數組的根對象,因爲您的消息數組位於result.messages.items

遍歷的消息,你應該做的

$.getJSON("/json/messages.json",function(result){ 
    $.each(result.messages.items, function(i, message){ 
     console.log(message.Subject) 
    }); 
    }); 
+0

優秀的存在, 謝謝。這是我疲憊的心靈可能整天看着它,仍然沒有看到明顯的那些問題之一:D這是非常有道理的。當我被允許時,我會在幾分鐘內接受答案。 –

0

項目本身是一個數組,以便即時猜測你至少需要訪問它想:

messages.items[0].Subject 
0

項目是一個數組。你應該遍歷它來獲取所有項目。

<script> 
    $.getJSON("/json/messages.json",function(result){ 
     $.each(result, function(i, messages){ 
      $.each(messages.items, function(index, item){ 
       console.log(item.Subject) 
      }); 

     }); 
     }); 
    </script> 
0

items屬性是一個數組,這樣你就不能使用items.Subject

循環通過陣列中的項目,而不是通過在根對象的屬性循環,:

$.getJSON("/json/messages.json",function(result){ 
    $.each(result.messages.items, function(i, item){ 
    console.log(item.Subject) 
    }); 
}); 
0

似乎存在與所述邏輯的問題。試試這個:

<script> 
     $.getJSON("/json/messages.json",function(result){ 
      $.each(result.items, function(i, item){ 
       console.log(item.Subject) 
      }); 
      }); 
     </script> 
0

你的對象以這種形式

MainObj---> messages -----> items---->Subject 

所以如果你需要打印的主題,那麼你必須以同樣的方式來訪問,因爲他們存在

result.messages.items.Subject