解析JSON數組我有用於返回一個POST請求(回聲)的陣列中的PHP腳本時:意外標記ü試圖從AJAX
array(3) {
["message"]=>
string(32) "The item was successfully saved"
["newItemId"]=>
int(9)
["newCustomFieldIds"]=>
string(3) "[9]"
}
我的AJAX請求:
$.ajax({
url: 'updateItemDetails.php',
method: 'post',
data: {
...
}
}).done(function(response) {
console.log(response); //correct
console.log(response['newCustomFieldIds']); //undefined
console.log(JSON.parse(response['newCustomFieldIds'])); //unexpected token u
});
第一的console.log生產:
{"message":"The item was successfully saved","newItemId":9,"newCustomFieldIds":"[9]"}
其是如預期。但是,第二個給出undefined
。
所以,當我JSON.parse,我得到Uncaught SyntaxError: Unexpected token u
!我試圖做的是讓"[9]"
真實的數組,即。 [9]
。
我不明白這一點。 newCustomFieldIds
肯定存在,因爲在登錄response
時,我可以看到它 - 爲什麼console.log(response['newCustomFieldIds'])
不工作?
嗯,現在我得到'意外的令牌a' ..!? (當我解析兩次) –
然後'response'不是你聲稱的值:https://jsfiddle.net/bu63quzb/。一般的解決方案非常簡單:如果您有一個包含JSON的字符串,請調用'JSON.parse'。閱讀[訪問/進程(嵌套)對象,數組或JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json)以瞭解更多關於如何訪問對象獲得你想要的價值。 –
http://i.stack.imgur.com/KhGY3.png就是我所看到的! –