jquery ajax: how to implement timeout when internet is not connected
I am trying to make an ajax request and I want to find out if the internet is not connected. So, I was thinking that if the ajax request gives a timeout error, it can somehow be equated to no internet connection (I know that is not correct). Anyhow, here's my code:
$.ajax({
url: 'http://example.net/getdata',
dataType: 'json',
data: 'product=all',
timeout: 3000,
success: function(data) {
if (data.success == 'yes') {
alert('I was successful');
} else {
alert('I failed');
}
},
error: function(objRequest, errortype) {
if (errortype == 'timeout') {
alert('I timed out');
}
}
});
I tried sending a request when the internet was not connected, and I thought I would receive a "开发者_如何转开发timeout" error after 3 seconds (since I have set timeout to 3000). But I received a "parseerror". Why did that happen?
What is the correct way to implement something like no internet connection?
I'm not sure why you are getting a "parseerror" but please see this fiddle:
http://jsfiddle.net/pgWCg/
JSFiddle allows you to send a data param for a delay to test timeout, so I've set delay to 3 seconds and your timeout value to 2 seconds, and it does indeed alert the "I timed out" message.
You can modify both values to ensure that the delay is working as expected.
精彩评论