Created
October 24, 2008 08:46
-
-
Save greut/19372 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ajax(obj) { | |
// data | |
obj.type = obj.type ? obj.type.toUpperCase() : "GET"; | |
obj.data = obj.data || ""; | |
obj.dataType = obj.dataType || "application/x-www-form-urlencoded"; | |
obj.aborted = false; | |
// callbacks | |
obj.success = obj.success || function() {}; | |
obj.error = obj.error || function() {}; | |
// init XHR | |
var xhr, xhrs = array(); | |
if(typeof XMLHttpRequest !== "undefined" ) { | |
xhrs.push([XMLHttpRequest, undefined]); | |
} else if(typeof ActiveXObject !== "undefined") { | |
xhrs.push([ActiveXObject,"Microsoft.XMLHTTP"]); | |
xhrs.push([ActiveXObject,"Msxml2.XMLHTTP"]); | |
xhrs.push([ActiveXObject,"Msxml2.XMLHTTP.3.0"]); | |
} | |
for(var i=xhrs.length;i--;) { | |
try { | |
xhr = new xhrs[i][0](xhrs[i][1]); | |
if(xhr) { | |
break; | |
} | |
} catch(e) {} | |
} | |
xhr.onreadystatechange = function() { | |
if(this.readyState == 4 && !obj.aborted) { | |
switch(this.status) { | |
case 200: | |
obj.success.call(obj, this); | |
break; | |
default: | |
obj.error.call(obj, this); | |
break; | |
} | |
if("timer" in obj) { | |
clearTimeout(obj.timer); | |
} | |
// IE memory leak | |
this.onreadystatechange = function(){} | |
} | |
} | |
xhr.open(obj.type, obj.url, true); | |
if(obj.type === "POST") { | |
xhr.setRequestHeader("Content-type", obj.dataType); | |
xhr.setRequestHeader("Content-length", obj.data.length); | |
xhr.setRequestHeader("Connection", "close"); | |
} | |
if("timeout" in obj && obj.timeout > 0) { | |
obj.timer = window.setTimeout(function() { | |
obj.aborted = true; | |
xhr.abort(); | |
obj.error.call(obj, xhr); | |
xhr = null; | |
clearTimeout(obj.timer); | |
}, obj.timeout); | |
} | |
xhr.send(obj.data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment