-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax.js
54 lines (52 loc) · 1.21 KB
/
ajax.js
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
49
50
51
52
53
54
function ajax(type,url,data,async,cache=true){
return new Promise(function(resolve,reject){
let xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
type = type.toUpperCase();
if(type ==='GET'){
let cacheA = [];
for (let i in data){
cacheA.push(i+'='+data[i]);
}
if(cache){
cacheA.push(new Date().getTime()+"=1");
}
if(url.indexOf("?")>-1){
url += '&'+cacheA.join('&');
}else{
url += '?'+cacheA.join('&');
}
cache = null;
xhr.open(type,url,async);
xhr.setRequestHeader("Content-type","application/json");
xhr.send();
}else if(type==='POST'){
if(url.indexOf("?")>-1&&cache){
url += '&'+(new Date().getTime()+"=1");
}
xhr.open(type,url,async);
xhr.setRequestHeader("Content-type","application/json");
xhr.send(JSON.stringify(data));
}else{
reject('error type')
}
xhr.onreadystatechange=function(){
console.log(xhr.readyState,xhr.status)
if(xhr.readyState==4 ){
if(xhr.status==200){
let obj = xhr.response;
if(typeof obj !=='object'){
obj = JSON.parse(obj);
}
resolve(obj);
}else{
reject('status error');
}
}
}
});
}