SyntaxError:JSON.parse:JSON 的第 1 行第 2 列出现意外字符

新手上路,请多包涵

我需要将此 div 附加到另一个 div ,但它给了我这个错误:

SyntaxError:JSON.parse:JSON 数据的第 1 行第 2 列出现意外字符

这是我的 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)
        }
    }
})

原文由 Ðr Ssamade 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 685
2 个回答

简单地改变

var respons = jQuery.parseJSON(response);

var respons = response;

解释:

如果您的 AJAX 调用的配置具有 dataType: json 您将获得一个 JavaScript 对象,因此不再需要使用 JSON.parse()。

原文由 Alfredo EM 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是解析 JSON 的一种骇人听闻且非正统的方式,但如果您仍想从 AJAX 调用中使用 JSON.parse() 或只是在已解析且不是字符串的 JSON 上使用,您可以使用 JSON.stringify() 在里面:

 var respons = JSON.parse(JSON.stringify(response));

原文由 Max Voisard 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题