附上完整代码
function ajax(json){
var xhr = new XMLHttpRequest();
var method = json.method;
var url = json.url;
var success = json.success;
var error = json.error;
var data = json.data||{};
switch(method){
case 'get':
xhr.open(method,url+'?'+fn(data),true);
xhr.send(null);
break;
case 'post':
xhr.open(method,url,true);
xhr.setRequestHeader('content-type','application/x-www-urlencoded');
xhr.send(fn(data));
break;
}
xhr.onreadystatechange = function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300||xhr.status===304){
success(JSON.parse(xhr.responseText))
}else{
error(xhr.status)
}
}
}
function fn(obj){
var arr = [];
for(var key in obj){
arr.push(key+'='+obj[key])
}
return arr.join('&')
}
}
使用:
ajax(
{
method:'',
url:'',
data:‘’,
success:function (res) {
console.log(res);
},
error:function (status) {
console.log(status);
}
}
);
对封装函数的个人理解以及其中代码解释:
https://blog.csdn.net/weixin_44845533/article/details/99098298