[英]Unexpected token u when trying to parse a JSON array from AJAX
I have a PHP script which is used for a POST request which returns (echos) the array: 我有一个PHP脚本,用于返回(echos)数组的POST请求:
array(3) {
["message"]=>
string(32) "The item was successfully saved"
["newItemId"]=>
int(9)
["newCustomFieldIds"]=>
string(3) "[9]"
}
My AJAX request: 我的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
});
The first console.log produces: 第一个console.log产生:
{"message":"The item was successfully saved","newItemId":9,"newCustomFieldIds":"[9]"}
which is as expected. 正如预期的那样。 However, the second one gives
undefined
. 但是,第二个给出
undefined
。
So, when I JSON.parse, I get Uncaught SyntaxError: Unexpected token u
! 因此,当我进行JSON.parse时,我得到了
Uncaught SyntaxError: Unexpected token u
! What I'm trying to do is to get the "[9]"
to a real array, ie. 我想做的是将
"[9]"
转换为真实数组,即。 [9]
. [9]
。
I don't understand this. 我不明白
newCustomFieldIds
definitely exists, because when logging the response
, I can see it -- so why doesn't the console.log(response['newCustomFieldIds'])
work? newCustomFieldIds
确实存在,因为在记录response
,我可以看到它-为什么console.log(response['newCustomFieldIds'])
不起作用?
You have to parse response
: 您必须解析
response
:
JSON.parse(response).newCustomFieldIds
If you want to convert the string "[9]"
to an array, you need to call JSON.parse
twice: 如果要将字符串
"[9]"
转换为数组,则需要调用JSON.parse
两次:
JSON.parse(JSON.parse(response).newCustomFieldIds)
However, the better solution would be to encode the value of newCustomFieldIds
as an array in the first place, ie the JSON should contain "newCustomFieldIds": [9]
. 但是, 更好的解决方案是首先将
newCustomFieldIds
的值编码为数组,即JSON应包含"newCustomFieldIds": [9]
。
Since you know that response['newCustomFieldIds']
returns undefined
, it doesn't make sense to try JSON.parse(response['newCustomFieldIds'])
. 由于您知道
response['newCustomFieldIds']
返回undefined
,因此尝试JSON.parse(response['newCustomFieldIds'])
没有意义。 It's the same as JSON.parse("undefined")
, but undefined
is not valid JSON. 与
JSON.parse("undefined")
,但undefined
无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.