"没有良好的"通过jQuery.ajax在Firefox加载客户端的JSON时警告客户端、加载、良好、jQuery

2023-09-10 14:17:46 作者:胜者为↗王

我使用jQuery的AJAX方法来获得一个静态的JSON文件。该数据从本地文件系统加载的,因此不存在服务器上,所以我不能改变的MIME类型。

I am using jQuery's ajax method to acquire a static JSON file. The data is loaded from the local file system, hence there is no server, so I can't change the MIME type.

这工作正常的Safari浏览器,但Firefox(3.6.3)报告文件是没有良好的。我知道,和审查,在这里对堆栈溢出类似的帖子:

This works fine in Safari, but Firefox (3.6.3) reports the file to be "not well-formed". I am aware of, and have reviewed, a similar post here on Stack Overflow:

"not良好的"在Firefox错误时加载的JSON文件XMLHtt prequest

我认为这是良好的我JSON:

I believe my JSON is well-formed:

{
    "_": ["appl", "goog", "yhoo", "vz", "t"]
}

我的Ajax调用非常简单:

My ajax call is straightforward:

$.ajax({
    url: 'data/tickers.json', 
    dataType: 'json',
    async: true,
    data: null,
    success: function(data, textStatus, request) {
        callback(data);
    }
});

如果我换一个文档标签的JSON:

If I wrap the JSON with a document tag:

<document>JSON data</document>

正如上文提到的其他堆栈溢出的问题,Ajax调用失败,并分析错误。

as was mentioned in the other Stack Overflow question referenced above, the ajax call fails with a parse error.

所以:有没有办法避免客户端的JSON文件读取时,Firefox的警告

So: is there a way to avoid the Firefox warning when reading in client-side JSON files?

推荐答案

有时候使用HTTP服务器是不是一种选择,这可能意味着将不会自动提供某些文件的MIME类型。从彼得·霍夫曼的答案适用于jQuery .getJSON Firefox 3的语法错误未定义,你做任何$ .getJSON(前使用此code)称:

Sometimes using an HTTP server is not an option, which may mean that MIME types won't be automatically provided for some files. Adapted from Peter Hoffman's answer for jQuery .getJSON Firefox 3 Syntax Error Undefined, use this code before you make any $.getJSON() calls:

$.ajaxSetup({beforeSend: function(xhr){
  if (xhr.overrideMimeType)
  {
    xhr.overrideMimeType("application/json");
  }
}
});

或者,如果你使用$阿贾克斯():

Or, if you're using $.ajax():

$.ajax({
  url: url,
  beforeSend: function(xhr){
    if (xhr.overrideMimeType)
    {
      xhr.overrideMimeType("application/json");
    }
  },
  dataType: 'json',
  data: data,
  success: callback
});