简单的封装一下,还有很多不足。主要就是封装了get和post请求,这个仿照jQuery的ajax写的。大致思路就是去判断一下有没有传url、区分请求的类型、根据请求的结果调用不用的回调函数。
//ajax函数
//1. type:方式 "get" "post"
//2. url:地址 url "demo.php"
//3.data:数据 "id=0&name=zhangsan"
//4.asynch:是否异步 true false
//5.dataType:返回数据的格式 "text" "json" "xml"
//6.success返回数据之后进行的操作 function(){}
export default function ajax(options){
//没有url 直接退出
if(!options.url){
alert('请输入URL');
return;
}
var type = options.type || 'GET';
var async = options.async==undefined?true:options.async;
var dataType = options.dataType || 'json';
var dataStr = "";
if(options.data){
if(typeof options.data=='string'){
dataStr = options.data;
}else{
for(var i in options.data){
dataStr+= i+'='+options.data[i]+'&'
}
dataStr = dataStr.slice(0,-1)
}
}
var xhr = new XMLHttpRequest();
if(type.toUpperCase() =='GET'){
if(dataStr){
xhr.open('GET',options.url+'?'+dataStr,async);
}else{
xhr.open('GET',options.url,async);
}
xhr.send();
}
if(type.toUpperCase() =='POST'){
xhr.open('POST',options.url,async);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
xhr.send(dataStr);
}
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
if(dataType=='text'){
options.success&&options.success(xhr.response);
}else if(dataType=='xml'){
options.success&&options.success(xhr.responseXML);
}else if(dataType=='json'){
options.success&&options.success(JSON.parse(xhr.response));
}
}else if(xhr.status ==404){
alert('请求失败');
}
}
}
}