javascript - 为什么 jQuery.parseJSON 在 Firefox 中无法解析这个有效的 JSON 文档?

标签 javascript jquery json firefox

服务器返回此 JSON 文档:

{
"username-found": true,
"question-required": true
}

成功通过 JSONLint 的有效性检查。

在网络浏览器中:

$.post('my_url', {"post":"data"}, function(data) {
  data = $.parseJSON(data);
});

代码在 Opera 12 浏览器中运行并成功解析 JSON 文档,但是在 Firefox 16 中,出现 JavaScript 错误并显示“格式不正确”。

JQuery 版本为 1.7.2。

我看不到我做错了什么,你知道吗?

编辑:

这和服务器返回 JSON 的方式有什么关系吗?这是:

return new StreamingResolution("text", new StringReader(json.toString()));

建议,我可能已经找到原因了。当我执行 alert(data) 时,Firefox 告诉我 data 是一个对象,Opera 告诉我 data 是 JSON 字符串。

最佳答案

解决方案 1(客户端)- 在 jQuery 请求中设置 DataType

我认为特定浏览器版本的内部结构有点不同(因为 jQuery 尝试自动检测数据类型,并在 JSON 响应的情况下在内部进行解析)并且 JSON 会自动在 FF 中编码,而不是在 Opera 中编码?

尝试添加数据类型,以便 jQuery 能够处理这个问题(我更喜欢这样):

$.post('my_url', {"post":"data"}, function(data) {
    // data should be an json object here
}, 'json');

这只是猜测。

OR 解决方案 2(服务器)- 发送 MIME 类型

您还可以从服务器发送正确的 MIME 类型,这样您就不必在客户端上设置 dataType。这取决于你,但我认为这将是正确的解决方案。

关于this答案应该是application/json

引用

jQuery 中如何自动检测 dataType?

Default: Intelligent Guess (xml, json, script, or html) The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

来源:http://api.jquery.com/jQuery.ajax/

关于javascript - 为什么 jQuery.parseJSON 在 Firefox 中无法解析这个有效的 JSON 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13079202/

相关文章:

javascript - 1 秒后隐藏 Canvas ctx.rect() - Javascript

javascript - 如何知道在 jquery 中选择了哪个单选按钮?

javascript - jQuery UI 对话框文本是否有换行选项?

javascript - 当不相关的 div 为空时更改文本

javascript - 错误: listen EADDRINUSE when running a Node. js脚本

javascript - 如何将 document.body 的所有子级放入包装器中?

javascript - 单击时使用 jquery 从数据网格行获取值

json - 想要 Groovy MarkupBuilder() 等同于对象的 JSONBuilder()

javascript - Google Finance JSON 回复在 Chrome、Firefox 中不起作用,但在 IE 11 中起作用

java - Json 中的控制字符导致 JsonParsingException