赞
踩
class Ajax {
constructor(xhr) {
xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
this.xhr = xhr;
}
send(options) {
let xhr = this.xhr;
let opt = {
type: options.type || 'GET',
url: options.url || '',
async: options.async || 'true',
dataType: options.dataType || 'json',
questring: options.questring || ''
};
return new Promise((resolve, reject) => {
xhr.open(opt.type,opt.url,opt.async);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4) {
if(xhr.status === 200){
if(opt.dataType === 'json'){
const data = JSON.parse(xhr.responseText);
resolve(data);
console.log(data);
}
}else {
reject(new Error(xhr.status || 'Server is fail.'));
}
}
};
xhr.onerror = () => {
reject(new Error(xhr.status || 'Server is fail.'));
};
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(opt.questring);
})
}
}
let ajax = new Ajax();
ajax.send({
type : 'POST',
url:'https://www.baidu.com/api/newsList.php'
});
经测试可用。
如有缺漏,请指出。谢谢。
挚谢阅读。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。