ajax我们经常会用到的,但网上找到的大部份ajax兼容性都不强,下面自己改了一个不错的兼容性很强的ajax函数,同时后面介绍的jquery ajax 兼容性也很强。
一、纯js实现的Ajax实例:
代码如下:var ajax = function() {};
ajax.prototype = {
request: function(method, url, callback, postVars) {
var xhr = this.createXhrObject();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
(xhr.status === 200) ?
callback.success(xhr.responseText, xhr.responseXML) :
callback.failure(xhr,status);
};
if (method !== "POST") {
url += "?" + JSONStringify(postVars);
postVars = null;
}
xhr.open(method, url, true);
xhr.send(postVars);
},
createXhrObject: function() {
var methods = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
],
i = 0,
len = methods.length;
for (; i < len; i++) {
try {
methods[i];
} catch(e) {
continue;
}
this.createXhrObject = methods[i];
return methods[i];
}
新闻热点
疑难解答
图片精选