2017-03-13 24 views
0

如何使用JQuery讀取像這樣的Json響應:{"result":{"_id":{"Timestamp":23232323, "Machine:4235245252"}, "Agency":"Crooars", "City":"New York", "State": "New Jersey"}}我想閱讀AgencyCityState,其他字段不相關。 我曾與一些嘗試這樣的:在JQuery中讀取Json字段

$.ajax({ 
type: 'post', 
url: urlPostGraduate, 
data: $("#formPostGrad").serialize(), 
success: function (result) { 
alert(result.Agency) // returns undefined 
alert(result._id.Agency) // it doesn't even show the alert 
alert(result["_id"].Agency) //neither 
} 
+0

嘗試alert(result.result.Agency); – shakib

+1

不使用'alert()',使用'console.log()'。然後使用'console.log(result)'。這是你所期待的嗎? –

回答

2

請注意,您的JSON的根密鑰響應爲result,接收響應的參數也爲result。因此,如果您想訪問響應的任何信息,則需要編寫result.result.your_key_name

例如,您需要編寫result.result.Agency以從響應中獲取Agency的值。

此外,這與jQuery無關,僅與訪問JavaScript中的JSON對象有關。

+0

好吧,它實際上與jQuery有關,因爲在過去,jQuery沒有智能的猜測來將響應轉換爲對象,他可能會想到一些事情。 – Fma

1

結果變量保存完整的JSON響應,並從內需要的結果的關鍵:

result.result.Agency