forked from liujianxi/share
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.js
77 lines (73 loc) · 1.85 KB
/
http.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
export function getParams(data){
let arr = [];
for (let name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
return arr.join('&');
}
/**
* 自定义http请求
*/
class Http {
get(url, params) {
let self = this;
let xmlhttp = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
let temp = JSON.parse(xmlhttp.responseText);
if (temp.errorCode == 0) {
resolve(temp);
} else if (temp.errorCode == 1) {
reject(temp);
} else {
reject(temp);
}
} else {
reject();
}
}
};
xmlhttp.open("POST",url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
let data=getParams(params);
xmlhttp.send(data);
});
},
post(url, params) {
let self = this;
let xmlhttp = new XMLHttpRequest();
return new Promise((resolve, reject) => {
//这里this指向xmlhttp
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
let temp = JSON.parse(xmlhttp.responseText);
if (temp.errorCode == 0) {
resolve(temp);
} else if (temp.errorCode == 1) {
reject(temp);
} else {
reject(temp);
}
} else {
reject();
}
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
xmlhttp.send(JSON.stringify(params));
});
}
}
let http = new Http();
export default http;
/**
*调用时:
* http.post('getData.php',params);
* http.get('getData.php',params);
*/