UPDATE: Since you are creating a Dashboard widget, I ran a number of tests.
I found that the $.ajax
call actually triggered an error when there was no internet connection. So I went about creating a XMLHTTPRequest object manually with great success. If you need JSON parsing, I suggest also including the json2.js parser.
Things I did to make this work:
- In Widget Attributes in Dashcode I clicked "Allow Network Access" (If you aren't using Dashcode, check the docs for the proper plist setting to turn this on)
- I used the following code:
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', state_change, true);
xhr.open("GET", url, true);
xhr.send(null);
function state_change(){
if(xhr.readyState == 4){
if(xhr.status == 200){
console.log('worked'); // Only works if running in Dashcode
// use xhr.responseText or JSON.parse(xhr.responseText)
} else if(xhr.status == 0) {
console.log('no internet'); // Only works if running in Dashcode
} else {
// Some other error
}
}
}
/End Update
I answered this by editing my answer to your original question since you asked it in the comments. After commenting I saw you posted this question.
To summarize, add the timeout
parameter to your $.ajax
call and set it to a low number (like 5000 milliseconds). Your error function will be called after the request times out.