繁体   English   中英

尝试从AJAX解析JSON数组时出现意外的令牌u

[英]Unexpected token u when trying to parse a JSON array from AJAX

我有一个PHP脚本,用于返回(echos)数组的POST请求:

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'])不起作用?

您必须解析response

JSON.parse(response).newCustomFieldIds

如果要将字符串"[9]"转换为数组,则需要调用JSON.parse两次:

JSON.parse(JSON.parse(response).newCustomFieldIds)

但是, 更好的解决方案是首先将newCustomFieldIds的值编码为数组,即JSON应包含"newCustomFieldIds": [9]


由于您知道response['newCustomFieldIds']返回undefined ,因此尝试JSON.parse(response['newCustomFieldIds'])没有意义。 JSON.parse("undefined") ,但undefined无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM