简体   繁体   English

JSON.parse抛出不合逻辑的语法错误:意外的令牌

[英]JSON.parse throwing illogical Syntax Error: Unexpected token

I have a problem with parsing the json string passed from a method in PHP over an AJAX call. 我在解析通过AJAX调用从PHP中的方法传递的json字符串时遇到问题。 The string is 字符串是

[{"type":"successful","message":"Prijava uspe\u0161na!"}] 

When I try to parse it in javascript with JSON.parse(the string) , I get an Unexpected token error in my console. 当我尝试使用JSON.parse(the string)在javascript中解析它时,我在控制台中收到意外的令牌错误。

There is no problem when I execute this on my localhost nothing is wrong even though I get the same response from the PHP script. 当我在本地主机上执行此操作时没有问题,即使我从PHP脚本获得了相同的响应,也没有错。

When I try the following in the success function of the ajax 当我在ajax的成功功能中尝试以下内容时

console.log(message);
console.log(JSON.stringify(message));
console.log(JSON.parse(message));

I get this 我明白了

[{"type":"successful","message":"Prijava uspe\u0161na!"}]  login:102
"\r\n\r\n[{\"type\":\"successful\",\"message\":\"Prijava uspe\\u0161na!\"}]\r\n\r\n" login:104
Uncaught SyntaxError: Unexpected token  login:104

And line 104 (well not really, the console points at it): 第104行(不是真的,控制台指向它):

console.log(JSON.parse(message));

I've tried replacing \\r\\n, ended up the same 我尝试替换\\ r \\ n,结果还是一样

I am really confused... 我真的很困惑

Your JSON has a BOM , which is not a valid token. 您的JSON具有BOM表 ,该BOM表不是有效令牌。

Ensure that whatever is sending your JSON is encoding it correctly without this BOM. 确保没有此BOM的所有发送JSON的代码均正确编码。

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

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