简体   繁体   English

使用 XMLHttpRequest 加载 JSON 文件时,Firefox 中出现“格式不正确”错误

[英]"not well-formed" error in Firefox when loading JSON file with XMLHttpRequest

I'm getting a "not well-formed" error in the error console of Firefox 3.0.7 when the JavaScript on my page loads a text file containing an object in JavaScript Object Notation format.当我页面上的 JavaScript 加载包含 JavaScript 对象表示法格式的对象的文本文件时,Firefox 3.0.7 的错误控制台中出现“格式不正确”错误。 If the file contains nothing but the JSON object, it produces the error.如果文件只包含 JSON 对象,则会产生错误。 If I wrap the object in <document></document> tags it does not produce the error.如果我将对象包装在 <document></document> 标签中,它不会产生错误。 The request succeeds either way, so I could just ignore it, but I don't want my error log filling up with these messages.无论哪种方式请求都会成功,所以我可以忽略它,但我不希望我的错误日志被这些消息填满。

Here is some example code to illustrate the problem.下面是一些示例代码来说明问题。 First, the "not well-formed" file called "data.json":首先,名为“data.json”的“格式不正确”文件:

{ a: 3 }

Now some code to load the file:现在一些代码来加载文件:

var req = new XMLHttpRequest();
req.open("GET", "data.json");
req.send(null);

Which produces the following error in the Firefox error console:这会在 Firefox 错误控制台中产生以下错误:

not well-formed格式不正确
file://path/to/data.json Line: 1 file://path/to/data.json 行:1
{ a: 3 } { a: 3 }
- ^ - ^

If data.json is modified to this:如果将 data.json 修改为:

<document>{ a: 3 }</document>

There is no error.没有错误。 I assumed that it is complaining because the plain JSON file is not a well formed XML document, so I tried overriding the MIME type before the "send" call to force it to load as plain text, but that didn't work.我认为它在抱怨是因为纯 JSON 文件不是格式良好的 XML 文档,所以我尝试在“发送”调用之前覆盖 MIME 类型以强制它作为纯文本加载,但这没有用。

var req = new XMLHttpRequest();
req.open("GET", "data.json");
req.overrideMimeType("text/plain");
req.send(null);
// Still produces an error!

I am going to continue with wrapping my JSON data in an XML document to get around whatever validation the XMLHttpRequest is performing, but I'd like to know if there is any way I can force it to just load plain text uncritically and not try to validate it.我将继续将我的 JSON 数据包装在 XML 文档中以绕过 XMLHttpRequest 正在执行的任何验证,但我想知道是否有任何方法可以强制它不加批判地加载纯文本而不是尝试验证它。 Alternatively, is there another method of loading data besides XMLHttpRequest that can be used with plain text?或者,除了 XMLHttpRequest 之外,还有其他加载数据的方法可以与纯文本一起使用吗?

Have you tried using the MIME type for JSON? 您是否尝试过使用MIME类型进行JSON?

application/json

You could also configure your server to send this MIME type automatically for .json files. 您还可以将服务器配置为自动为.json文件发送此MIME类型。

Firstly, true JSON is much stricter than JavaScript, and to be valid JSON, you have to have your keys quoted. 首先,真正的JSON比JavaScript更严格,要成为有效的JSON,您必须引用密钥。

 { "a": 3 } 

Also, as you are using a bare XMLHttpRequest, which generally expects to receive an XML result unless MIME headers specify strictly otherwise. 此外,当您使用裸XMLHttpRequest时,通常希望接收XML结果,除非MIME标头严格指定。

You may however wish to make your own life easier by simply using a JavaScript framework such as jQuery which will abstract away all this problem for you and deal with all the nasty edge cases. 然而,您可以通过简单地使用jQuery之类的JavaScript框架来让自己的生活变得更轻松,这样可以为您抽象出所有这些问题并处理所有令人讨厌的边缘情况。

$.getJSON("data.json",{}, function( data ){ 
  /*  # do stuff here  */ 
});

Additionally, if you use both strict JSON and use a library to abstract it for you, when browsers start having native JSON parsers the library will be able to transparently make use of these and get a significant speed improvement. 此外,如果您同时使用严格的JSON并使用库来为您抽象,那么当浏览器开始使用本机JSON解析器时,库将能够透明地利用这些并获得显着的速度提升。

( This is slated to happen sooner than later, and when it happens, your users will get a silent upgrade with no effort required! ). (这预计会在以后发生,当它发生时,您的用户将获得无需升级的静默升级!)。

当Content-Type完全为空(从而绕过自然类型检测)时,也会发生这种情况。

I found the same error message but from a very different cause. 我发现了相同的错误消息,但原因却截然不同。 After a little time fruitlessly changing the JSON content, realized that I had accidentally restarted the page running off the local file system (file://Users/me/Sites/mypage.html) rather than the server (http://localhost/~me/Sites/mypage.html). 经过一段时间无果而终地改变JSON内容,意识到我不小心重新启动了运行本地文件系统的页面(文件://Users/me/Sites/mypage.html)而不是服务器(http:// localhost / 〜我/网站/的mypage.html)。

实际应该是{“a”:3}。

I was also getting the same warning message with XMLHttpRequest() (in FireFox), when requesting resources marked as Content-Type: application/json by the server. 当请求服务器标记为Content-Type: application/json的资源时,我也在使用XMLHttpRequest() (在FireFox中)获得相同的警告消息。

What did the trick for me was to explicitly set the XMLHttpRequest.responseType property to json on the request object. 对我来说,诀窍是在请求对象上显式设置XMLHttpRequest.responseType属性为json Eg, 例如,

var request = new XMLHttpRequest();
request.onreadystatechange = function() { ... }
...
request.open('GET','https://random-domain.com/random-path',true);
request.responseType = 'json';
...
request.send();
Browser --- request expects a given content-type ---> Server
        <-- response contains content-type ----------

Firefox looks at the HTTP Content-Type header . Firefox查看HTTP Content-Type标头 If the server HTTP response header does not match the expectations of your browser code it will complain with this message. 如果服务器HTTP响应标头与您的浏览器代码的期望不符,它将抱怨此消息。

IMHO this error message could have been a lot better, like "Expecting response Content-Type header ... but found ...". 恕我直言这个错误信息可能会好很多,如“期待响应内容类型标题......但发现......”。

Unless there is a specific reason for opening your HTML directly from the disk ( file:// ), you should do yourself a favor and open it served by a local HTTP server ( http:// ), like the prototype user has written .除非有直接从磁盘 ( file:// ) 打开 HTML 的特定原因,否则您应该帮自己一个忙并打开由本地 HTTP 服务器 ( http:// ) 提供的服务,就像原型用户所写的. This will fix this issue because the MIME type will be set correctly, as jthompson suggested .这将解决这个问题,因为MIME 类型将被正确设置,如 jthompson 建议的

Thanks to that you will also not run into another issue, like " Reason: CORS request not HTTP ", and possibly others as browsers are getting more and more suspicious when they are asked to open files on the local disk - and for good reasons (security!).多亏了这一点,您也不会遇到另一个问题,例如“ 原因:CORS 请求不是 HTTP ”,并且可能还有其他问题,因为当他们被要求打开本地磁盘上的文件时,浏览器可能会变得越来越可疑 - 并且有充分的理由(安全!)。


If you have Python on your system then the (arguably) easiest way to run a local HTTP server is:如果您的系统上有 Python,那么运行本地 HTTP 服务器的(可以说是)最简单的方法是:

Mac/Linux: python3 -m http.server Mac/Linux: python3 -m http.server

Windows: python -m http.server or py -3 -m http.server Windows: python -m http.serverpy -3 -m http.server

The files from the current working directory will then be served under http://localhost:8000/然后将在 http://localhost:8000/ 下提供当前工作目录中的文件


PS If you upvote my answer then please also upvote the other helpful answers linked by me. PS 如果您对我的回答投赞成票,那么也请对我链接的其他有用答案投赞成票。 Thanks!谢谢! 😊 😊

Kent, I disagree. 肯特,我不同意。

The following IS "valid" JSON: 以下IS “有效”JSON:

{ a: 3 }

JavaScript object property names do NOT have to be strings. JavaScript对象属性名称不必是字符串。

The problem is one of MIME type, not JSON/JavaScript syntax. 问题是MIME类型之一,而不是JSON / JavaScript语法。

I just solved this very issue by adding json as "text/javascript" to my webserver mime types file: 我刚刚通过将json添加为“text / javascript”到我的webserver mime类型文件来解决这个问题:

text/javascript                 js, json

The "not well-formed" error disappeared. “形式不好”的错误消失了。 The browser (FireFox) assumed, incorrectly, that the .json file was XML. 浏览器(FireFox)错误地假定.json文件是XML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM