JSON.parse抛出不合逻辑的语法错误:意外的令牌 [英] JSON.parse throwing illogical Syntax Error: Unexpected token

查看:61
本文介绍了JSON.parse抛出不合逻辑的语法错误:意外的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在解析通过AJAX调用从PHP中的方法传递的json字符串时遇到问题.字符串是

I have a problem with parsing the json string passed from a method in PHP over an AJAX call. The string is

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

当我尝试使用 JSON.parse(字符串)在javascript中对其进行解析时,在控制台中出现了意外的令牌错误.

When I try to parse it in javascript with JSON.parse(the string), I get an Unexpected token error in my console.

当我在本地主机上执行此操作时没有问题,即使我从PHP脚本获得了相同的响应,也没什么错.

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.

当我在ajax的成功功能中尝试以下操作时

When I try the following in the success function of the ajax

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

我明白了

[{"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

第104行(不是真的,控制台指向它):

And line 104 (well not really, the console points at it):

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

我尝试替换\ r \ n,结果还是一样

I've tried replacing \r\n, ended up the same

我真的很困惑...

推荐答案

您的JSON具有 BOM ,这不是有效的令牌.

Your JSON has a BOM, which is not a valid token.

确保在没有此BOM的情况下,发送您的JSON的任何内容都能正确编码.

Ensure that whatever is sending your JSON is encoding it correctly without this BOM.

这篇关于JSON.parse抛出不合逻辑的语法错误:意外的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆