“格式不正确"使用 XMLHttpRequest 加载 JSON 文件时 Firefox 中的错误 [英] "not well-formed" error in Firefox when loading JSON file with XMLHttpRequest

查看:17
本文介绍了“格式不正确"使用 XMLHttpRequest 加载 JSON 文件时 Firefox 中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我页面上的 JavaScript 加载包含 JavaScript 对象表示法格式的对象的文本文件时,我在 Firefox 3.0.7 的错误控制台中收到格式不正确"错误.如果文件只包含 JSON 对象,则会产生错误.如果我将对象包装在 <document></document>标记它不会产生错误.无论哪种方式请求都会成功,所以我可以忽略它,但我不希望我的错误日志被这些消息填满.

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. If the file contains nothing but the JSON object, it produces the error. If I wrap the object in <document></document> tags it does not produce the error. The request succeeds either way, so I could just ignore it, but I don't want my error log filling up with these messages.

这是一些示例代码来说明问题.首先,名为data.json"的格式不正确"的文件:

Here is some example code to illustrate the problem. First, the "not well-formed" file called "data.json":

{ a: 3 }

现在一些加载文件的代码:

Now some code to load the file:

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

在 Firefox 错误控制台中产生以下错误:

Which produces the following error in the Firefox error console:

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

not well-formed
file://path/to/data.json Line: 1
{ a: 3 }
- ^

如果将data.json修改成这样:

If data.json is modified to this:

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

没有错误.我认为它是在抱怨,因为纯 JSON 文件不是格式良好的 XML 文档,因此我尝试在发送"调用之前覆盖 MIME 类型以强制将其加载为纯文本,但这没有用.

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.

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

我将继续将我的 JSON 数据包装在 XML 文档中以绕过 XMLHttpRequest 正在执行的任何验证,但我想知道是否有任何方法可以强制它不加批判地加载纯文本,并且不要试图验证它.或者,除了 XMLHttpRequest 之外,还有没有其他的加载数据的方法可以和纯文本一起使用?

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. Alternatively, is there another method of loading data besides XMLHttpRequest that can be used with plain text?

推荐答案

您是否尝试过将 MIME 类型用于 JSON?

Have you tried using the MIME type for JSON?

application/json

您还可以将服务器配置为自动为 .json 文件发送此 MIME 类型.

You could also configure your server to send this MIME type automatically for .json files.

这篇关于“格式不正确"使用 XMLHttpRequest 加载 JSON 文件时 Firefox 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆