Skip to content

Commit

Permalink
refactor Ajax sending with regard to timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
mislav committed Sep 4, 2011
1 parent 41e6999 commit f1ef348
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 36 deletions.
33 changes: 11 additions & 22 deletions src/ajax.js
Expand Up @@ -141,14 +141,14 @@
}

var mime = settings.accepts[settings.dataType],
xhr = $.ajaxSettings.xhr(), timeoutID;
xhr = $.ajaxSettings.xhr(), abortTimeout;

settings.headers = $.extend({'X-Requested-With': 'XMLHttpRequest'}, settings.headers || {});
if (mime) settings.headers['Accept'] = mime;

xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
clearTimeout(timeoutID);
clearTimeout(abortTimeout);
var result, error = false;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) {
if (mime == 'application/json' && !(/^\s*$/.test(xhr.responseText))) {
Expand All @@ -171,29 +171,18 @@
if (settings.contentType) settings.headers['Content-Type'] = settings.contentType;
for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name]);

var sendRequest = function () {
if (settings.beforeSend(xhr, settings) === false) {
xhr.abort();
return false;
}
xhr.send(settings.data);
};

var handleTimeout = function() {
if (xhr) {
xhr.onreadystatechange = function() { };
xhr.abort();
}
settings.error(xhr, 'timeout');
};

if (settings.timeout > 0) {
timeoutID = setTimeout(handleTimeout, settings.timeout);
}
if (sendRequest() === false) {
if (settings.beforeSend(xhr, settings) === false) {
xhr.abort();
return false;
}

if (settings.timeout > 0) abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty;
xhr.abort();
settings.error(xhr, 'timeout');
}, settings.timeout);

xhr.send(settings.data);
return xhr;
};

Expand Down
14 changes: 0 additions & 14 deletions test/ajax.html
Expand Up @@ -42,20 +42,6 @@ <h1>Zepto Ajax unit tests</h1>
});
},

testAjaxNotNullTimeout: function (t) {
var startTime = new Date();
t.pause();
$.ajax({
url: 'fixtures/ajax_load_simple.html',
timeout: 300,
beforeSend: function () {
t.resume(function () {
this.assert(new Date() - startTime > 300);
});
}
});
},

testAjaxNullTimeout: function (t) {
var startTime = new Date();
t.pause();
Expand Down

0 comments on commit f1ef348

Please sign in to comment.