2013-09-27 75 views
0

嗨,我有以下代碼:。每個解析JSON返回undefined

$.ajax({'type':'POST', 'url':'https://www.123.com/site/gethistory', 
     'data':{'a': this.username, 'b': username}, 
     'success':function(history){ 
      alert(history); 
      var codes = jQuery.parseJSON(history); 
      $.each(codes, function(key, value) { 
       alert(key); 
      }); //each 
     }, 
     'error':function(){ 
     } 
     }); //ajax 

眼下的關鍵是不確定的。而我試圖提醒(value.text),它仍然給我未定義。


歷史警覺,因爲這:

[{ 「演示」:{ 「文」: 「喜 人」, 「時間」: 「1380167419」}, 「管理員」:{ 「text」:「hi」,「time」:「1380167435」},「demo」:{「text」:「this works flawless now。」,「time」:「1380167436」},文 「:」 我們正在 基本上是與這個工作/」, 「時間」: 「1380167443」}}]

+0

jquey版本用過嗎? –

+0

@ArunPJohny 1.7.1 – jackhao

+0

你打開控制檯並檢查parseJSON是否拋出錯誤? – adeneo

回答

1

它在這個fiddle正常工作。但是,您的JSON存在問題。

雖然在語法上是正確的,它被構造爲使得要返回一個對象的陣列具有多個屬性的所有具有相同名稱:

[ 
    { "demo":{ 
     "text":"hi man", 
     "time":"1380167419" 
    }, 
    "admin":{ 
     "text":"hi", 
     "time":"1380167435" 
    }, 
    "demo":{ 
     "text":"this works flawless now.", 
     "time":"1380167436" 
    }, 
    "demo":{ 
     "text":"we are basically done with this/", 
     "time":"1380167443" 
    } 
    } 
] 

每個連續demo將覆蓋前一個所以你只會看到最後的demo屬性。

+0

非常感謝您的幫助。我現在明白了這個問題! – jackhao

+0

但是,如何在不寫入「value.demo.text」的情況下訪問該項目?我可以寫出「value.text」嗎? – jackhao

+0

您不能使用'value.text',因爲'text'不是'value'的屬性:它是'demo'的一個屬性。如果您需要訪問所有'demo'屬性,則需要更正JSON格式(服務器端修補程序),或者編寫一個能夠理解您特定數據格式的自定義JSON解析器。 – 2013-09-27 00:41:52

0

貌似有什麼不對您的JSON。嘗試提醒代碼並確保解析的JSON格式正確,即鍵/值對

+0

我試過警報代碼,但它只返回對象對象... – jackhao

+0

看到http://api.jquery.com/jQuery.parseJSON/你可以檢查codes.demo codes.admin等... – avrono

+0

是啊,它看起來像它是在控制檯中爲null。 – jackhao

0

無需使用jQuery來解析JSON。只是var codes = JSON.parse(history)

$.each(codes, function(k, v){ 
    console.log(v) 
}); 
+0

'$ .parseJSON'更具可移植性,因爲一些舊的瀏覽器沒有'JSON.parse'。在這種情況下,'jQuery'提供了它自己的實現。 – Barmar