Javascript SyntaxError: JSON.parse: JSON 第 1 行第 2 列的意外字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38412574/
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 at line 1 column 2 of the JSON
提问by Dr Ssamade
I need to append this div to another div , but it give me this error :
我需要将此 div 附加到另一个 div ,但它给了我这个错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
SyntaxError: JSON.parse: JSON 数据第 1 行第 2 列的意外字符
This is my javascript code:
这是我的 javascript 代码:
var str = {'message': message,'text': text};
$.ajax({
type: "POST",
url: "api/reply",
data: str,
dataType: "json",
cache: false,
success: function(response)
{
var respons = jQuery.parseJSON(response);
var type = respons.status
if (type == 'success') {
$("<div></div>").html(respons.message).appendTo("#messages");
}
else
{
toastr.error(respons.message)
}
}
})
回答by Alfredo EM
Try this:
尝试这个:
change var respons = jQuery.parseJSON(response);
to var respons = response;
更改var respons = jQuery.parseJSON(response);
为var respons = response;
Explanation:
解释:
If the configuration is dataType: json, you'll get a javascript object is no longer necessary JSON.parse
如果配置为 dataType: json,你会得到一个 javascript 对象不再需要 JSON.parse
回答by Max Voisard
This is a hackish and unorthodox way of parsing JSON, but if you still want to use JSON.parse()
from an AJAX call or simply on JSON that is already parsed and isn't a string, you can use JSON.stringify()
inside it:
这是解析 JSON 的一种骇人听闻的非正统方式,但如果您仍想JSON.parse()
从 AJAX 调用中使用或仅在已解析且不是字符串的 JSON 上使用,您可以JSON.stringify()
在其中使用:
var respons = JSON.parse(JSON.stringify(response));
回答by Tal87
the values in your object seem to be undefined.
change
var str = {'message': message,'text': text};
to
var str = {message: 'message',text: 'text'};
您对象中的值似乎未定义。更改
var str = {'message': message,'text': text};
为
var str = {message: 'message',text: 'text'};
回答by Nalan Madheswaran
Problem is you're not parsing a string, you're parsing an already parsed object.
问题是您不是在解析字符串,而是在解析已解析的对象。