!function() {
$z = {};
$z.isEmpty = function(arg) {
return Boolean(arg === "" || arg === undefined || arg === null)
}
$z.ajax = (function(obj) {
function ajax(obj) {
// var xhr = new
var type = obj.type.toLowerCase();
type = (type == 'get' || type == "post") ? type : "get";
this.type = type;
// this.data = this.type=="post"?obj.data:this.KVToString(obj.data);
this.data = obj.data && this.KVToString(obj.data);
//如果是data为空,那么到以后判断。
this.async = obj.async == false ? obj.async : true;
this.url = obj.url;
this.xhr = null;
this.success = obj.success;
this.error = obj.error;
};
// ajax.prototype.addHeader = function(xhr, headers) {
// for (var i in headers) {
// xhr.setRequestHeader(i, headers[i]);
// }
// }
ajax.prototype.KVToString = function(obj) {
var result = [];
if (typeof(obj) != "object") return obj;
for (var i in obj) {
result.push([i, obj[i]].join("="))
}
return result.join("&")
}
ajax.prototype.post = function(xhr) {
//如果没有数据的话,那么新建实例对象调用init的时候,只会调用get方式。
// 所以只要调用,一定会有数据。
this.xhr.open("post", this.url, this.async);
// this.xhr.setRequestHeader("content-type", "application/x-www-form-urlencode")
this.xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// this.xhr.setRequestHeader("x-requested-with", "XMLhttpRequest");
console.log(this.data);
console.log(typeof this.data);
console.log(this.url);
this.xhr.send(this.data);
}
ajax.prototype.get = function(xhr) {
if (this.data) {
if (!/\?/.test(this.url)) {
this.url += "?" + this.data;
} else {
this.url += this.data;
}
}
console.log(this.url);
this.xhr.open("get", this.url, this.async)
this.xhr.setRequestHeader("x-requested-with", "XMLHttpRequest");
this.xhr.send();
}
ajax.prototype.init = function() {
var that = this;
if (!this.url) {
throw new Error("url不能为空!");
}
this.xhr = new XMLHttpRequest();
if (!this.data) {
this.get();
} else {
if (this.type == "get") {
this.get()
} else {
this.post()
}
}
if (this.async == true) {
this.xhr.onreadystatechange = function() {
if (that.xhr.readyState == 4) {
if (that.xhr.status == 200 || that.xhr.status == 304) {
that.success && that.success(that.xhr.responseText);
} else {
that.error && that.error(that.xhr.status)
}
}
}
} else {
if (this.xhr.status == 200 || this.xhr.status == 304) {
this.success && this.success(this.xhr.responseText);
} else {
this.error && this.error(this.xhr.status);
}
}
}
return new ajax(obj).init();
});
if ($z.isEmpty(window.$z)) window.$z = $z
}();
原生js的ajax封装
最新推荐文章于 2019-04-16 16:05:56 发布