手动实现ajax

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function ajax(option){
option=option||{};
option.type=option.type||'get';
option.data=option.data||{};
option.dataType=option.dataType||'text';

let xhr=new XMLHttpRequest();

let arr=[];
for(let name in option.data){
arr.push(`${encodeURIComponent(name)}=${encodeURIComponent(option.data[name])}`);
}
let strData=arr.join('&');

if(option.type=='post'){
xhr.open('POST',option.url,true);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(strData);
}else{
xhr.open('GET',option.url+'?'+strData,true);
xhr.send();
}

//接收
xhr.onreadystatechange=()=>{
if(xhr.readyState==4){
if(xhr.status>=200 && xhr.status<300 ||xhr.status==304){
let data=xhr.responseText;
switch(option.dataType){
case 'json':
if(window.JSON && JSON.parse){
data=JSON.parse(data);
}else{
data=eval('('+str+')');
}
break;
case 'xml':
data=xhr.responseXML;
break;
}

option.success && option.success(data);
}else{
options.error && options.error();
}
}
}
}
分享