function ajax(options){
var promise= new Promise((resolve,reject)=>{
var xhr = null;
var params = formsParams(options.data);//key=value&key=value;
console.log(params)
//创建对象
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 连接
if(options.type == "GET"){
if(params!=""){
xhr.open(options.type,options.url + "?"+ params,options.async);
}else{
xhr.open(options.type,options.url);
}
xhr.send(null)
} else if(options.type == "POST"){
xhr.open(options.type,options.url,options.async);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(params);
}
xhr.onload = function(){
/* IE的script 元素只支持onreadystatechange事件,不支持onload事件。
FireFox,Opera, Chorme, IE11+ 和Safari3+的script 元素不支持onreadystatechange事件,只支持onload事件。 */
if(this.status == 200){
resolve(JSON.parse(this.response));
}else{
reject('加载失败')
}
}
xhr.onerror=function(){
reject(this)
}
function formsParams(data){
var arr = [];
for(var prop in data){
arr.push(prop + "=" + data[prop]);
}
//console.log(arr)//[0: "name=张三",1: "age=18"]
return arr.join("&");
}
})
return promise
}
调用:
ajax({
url : " https://autumnfish.cn/personalized/mv", // url---->地址
type : "GET", // type ---> 请求方式
async : true, // async----> 同步:false,异步:true
}).then(data=>{
console.log(data)
},reason=>{
console.log(reason)
})