Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

"not well-formed" warning when loading client-side JSON in Firefox via jQuery.ajax

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.

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 well-formed" error in Firefox when loading JSON file with XMLHttpRequest

I believe my JSON is well-formed:

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

My ajax call is straightforward:

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

If I wrap the JSON with a document tag:

<document>JSON data</document>

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...