سؤال

I have the following script whose ultimate purpose will be to fetch a local JSON file and populate a list with its contents. The problem is the file is never retrieved, but instead the fail function is called, and, bafflingly, the argument to the function contains the contents of the JSON file as 'responseText'. What gives?

In the worst case scenario, I could just turn the responseText into a JSON object and then use that to populate my list, but I'd rather figure out why this isn't working the way it's supposed to.

$( function() {
$.getJSON("public/data/opps.json", function(data) {
    console.log(data); // Never executes
})
  .fail(function(msg) {
      console.log(msg['responseText']); // Prints the contents of opps.json as a string
  });
});
هل كانت مفيدة؟

المحلول

The problem is that opps.json is not a valid JSON file.

When I tried your code and ensured the contents were JSON, it worked. For instance, if opps.json is:

[1,2,3]

Everything works as expected. however, if it's something like:

xyz

Then it fails.

Also, put a different message in your .fail (eg: console.log('FAIL')) to make sure the failure shows up, so you can see what's happening.

نصائح أخرى

I think it's very likely that your JSON file is not valid, e.g. there are syntax errors. This was mentioned in jQuery's documentation, too:

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

In short, jQuery will try to parse the JSON retrieved using the $.parseJSON(). If it fails, then it would pass the invalid JSON to the fail handler, not the success handler.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top