It seems very inconvenient that jQuery's $.getJSON
silently fails when the data returned is not valid JSON. Why was this implemented with silent failure? What is the easiest way to perform getJSON with better failure behavior (e.g. throw an exception, console.log()
, or whatever)?
相关问题
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
You can use
$.ajax
instead, and set thedataType
options to "json". From the documentation:Straight from the documentation:
As the documentation page says, getJSON is simply a shorthand method for
To get failure behavior, you can use $.ajax like this:
you can use
If you want to see the cause of the error, use the full version
If your JSON is not well-formed, you will see something like
If the URL is wrong, you will see something like
If you are trying to get JSON from another domain, violating the Same-origin policy, this approach returns an empty message. Note that you can work around the Same-origin policy by using JSONP (which has it's limitations) or the preferred method of Cross-origin Resource Sharing (CORS).
If you're requesting JSONP as the response, you will get a silent fail if there is no response (e.g. network outage). See this thread for details.
You should have a look at the docs for this API... it has a .error on it.
http://api.jquery.com/jQuery.getJSON/