jQuery 语法错误:JSON.parse:意外字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19824224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SyntaxError: JSON.parse: unexpected character
提问by alias51
I have a JSON parse error that I can't debug. Code below:
我有一个无法调试的 JSON 解析错误。代码如下:
$(document).on('submit', '#confirmreset', function(event) {
event.preventDefault();
var action_url = $(this).attr("action");
alert_box_register("Resetting password...");
console.log(action_url);
var postData = $(this).serializeArray();
console.log(postData);
$.post(action_url, postData, function(data) {
console.log(data);
var obj = $.parseJSON(data);
alert_box_register(obj.message);
});
});
And the JSON:
和 JSON:
{
"status": "success",
"message": "A temporary password has been emailed to you."
}
In Firefox the error is "SyntaxError: JSON.parse: unexpected character", in Chrome it's "Uncaught SyntaxError: Unexpected token C "
在 Firefox 中,错误是“SyntaxError:JSON.parse:意外字符”,在 Chrome 中是“Uncaught SyntaxError:Unexpected token C”
Any ideas?
有任何想法吗?
*EDIT: This works fine on my localhost setup. *
*编辑:这在我的本地主机设置上工作正常。*
回答by Explosion Pills
You don't need to call $.parseJSON
if the server is sending valid JSON as jQuery will parse it automatically when it retrieves the response. I don't know the exact criteria, but if you set the Content-type: application/json
header it definitelywill.
$.parseJSON
如果服务器正在发送有效的 JSON,则不需要调用,因为 jQuery 会在检索响应时自动解析它。我不知道确切的标准,但如果你设置Content-type: application/json
标题,它肯定会。
回答by atomh33ls
This error can be caused by using single quotation marks ('
) instead of double ("
) for strings.
对字符串使用单引号 ( '
) 而不是双引号 ( )可能会导致此错误"
。
The JSON specrequires double quotation marks for strings.
的JSON规范需要字符串双引号。
See also:
也可以看看: