簡體   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