Promise封装XMLHttpRequest
mtonhuang opened this issue · 0 comments
mtonhuang commented
// tools.js
/* 封装 XMLHttpRequest*/
// 序列化参数
function serialize(data) {
if (!data) return "";
var pairs = [];
for (var name in data) {
if (!data.hasOwnProperty(name)) continue;
if (typeof data[name] === "function") continue;
var value = data[name].toString();
name = encodeURIComponent(name);
value = encodeURIComponent(value);
pairs.push(name + "=" + value);
}
return pairs.join("&");
}
// 创 Ajax 请求对象,兼容ie8,ie9
function XHR() {
var xObj;
if (window.XMLHttpRequest) {
xObj = new XMLHttpRequest();
} else if (window.ActiveXObjext) {
xObj = new ActiveXObject();
}
return xObj;
}
// 封装
const ajaxForPromise = function(params) {
var data = params.data;
var url = params.url;
var method = params.method || "GET";
var responseType = params.responseType || "json";
var setHeader = params.setHeader;
var open = params.open || true;
return new Promise((resolve, reject) => {
// promise封装
var xhr = XHR();
var params = null;
xhr.onreadystatechange = handler;
if (method.toUpperCase() === "GET") {
url = url + "?" + serialize(data);
} else if (method.toUpperCase() === "POST") {
params = serialize(data);
}
xhr.open(method, url, open);
if (setHeader) {
xhr.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded;charset=UTF-8"
);
}
xhr.responseType = responseType;
xhr.send(params);
function handler() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response); // 正确回调
} else {
reject(new Error(this.statusText)); // 错误回调
}
}
});
};
export {
ajaxForPromise
};