实现Get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function getJSON(url) {
return new Promise(function (resolve, reject) {
var XHR = new XMLHttpRequest();
XHR.open("GET", url, true);
XHR.send();
XHR.onreadystatechange = function () {
if (XHR.readyState == 4) {
if (XHR.status == 200) {
try {
var response = JSON.parse(XHR.responseText);
resolve(response);
} catch (e) {
reject(e);
}
} else {
reject(new Error(XHR.statusText));
}
}
};
});
}
//用法
getJSON(url).then((resp) => console.log(resp));