从PHP制成的数组中使用JSON.parse时出现“意外令牌" [英] 'Unexpected token' when using JSON.parse from array made in PHP
问题描述
我正尝试AJAX AJAX数组,但由于某些原因,当我使用JSON.parse时,出现错误:Uncaught SyntaxError:Unexpected token
I'm trying to AJAX a JSON array but for some reason when I use JSON.parse it gives me the error: Uncaught SyntaxError: Unexpected token
这是我的PHP:
$infoJson = array('info' => array());
while($row = mysqli_fetch_array($query))
{
array_push($infoJson['info'],
[
'section' => $row['section'],
'source' => $row['source'],
'project' => $row['project'],
'client' => $row['client'],
'date' => $row['date'],
'id' => $row['id']
]);
}
echo json_encode($infoJson);
这是Javascript:
And here is the Javascript:
request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if(request.readyState == 4 && request.status == 200)
{
var response = request.responseText;
response = JSON.parse(response);
}
}
request.open('GET','http:edit.php?requestedArray=printArray',true);
request.send();
这也是PHP所呼应的:
Also here is exactly what the PHP is echoing:
{"info":[{"section":"printArray","source":"http:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/7\/7a\/SNES-Controller.jpg\/1280px-SNES-Controller.jpg","project":"SNES","client":"Nintendo","date":"1990","id":"7"},{"section":"printArray","source":"http:\/\/ecx.images-amazon.com\/images\/I\/81Q0l1t%2BaJL._SL1500_.jpg","project":"Playstation","client":"Sony","date":"1994","id":"8"},{"section":"printArray","source":"http:\/\/upload.wikimedia.org\/wikipedia\/commons\/e\/ed\/Xbox-360-S-Controller.png","project":"Xbox 360","client":"Microsoft","date":"2005","id":"9"}]}
如果我不使用JSON.parse和console.log响应,则会以字符串形式接收它.
If I don't use JSON.parse and console.log response, I do receive it as a string.
推荐答案
除了字符串开头的无效,不可见字符'\ufeff'
之外,您的输出可以很好地解析.这是 UTF-16字节顺序标记.您可能在Content-Type
标头中发送的字符串中的charset
不正确/丢失.
Your output parses fine, except for the invalid, invisible character '\ufeff'
at the beginning of the string. This is the UTF-16 byte order mark. You are probably sending the string with an incorrect/missing charset
in your Content-Type
header.
这篇关于从PHP制成的数组中使用JSON.parse时出现“意外令牌"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!