promise封装ajax

用Promise封装一个AJAX函数

AJAX即“Asynchronous JavaScript and XML”(异步的JavaScript与XML技术),
AJAX的优点是不重载当前页面的情况下,可以向服务器请求新内容。

发起AJAX的过程:

1,创建XMLHttpRequest对象

1
const xhr = new XMLHttpRequest();

2,监听xhr的readyState变化

1
2
3
4
5
6
7
8
9
10
11
    xhr.onreadystatechange = function () {
// readyState为4的时候已接收完毕
if (xhr.readyState === 4) {
// 状态码200表示成功
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log(xhr.status);
}
}
};

3,open 规划请求参数

1
2
3
4
// method  Get Post
// URL 请求地址
// bool 是否异步
xhr.open(method, url, true);

4,send 发送请求

1
xhr.send();

利用promise封装

接下来,用Promise简单的封装一个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
49
50
51

function ajax(method, url, params) {
return new Promise((resolve, reject) => {
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 状态改变时的回调
xhr.onreadystatechange = function () {
// readyState为4的时候已接收完毕
if (xhr.readyState === 4) {
// 状态码200表示成功
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.status);
}
}
};

// get
if (method === 'get' || method === 'GET') {
if (typeof params === 'object') {
// params拆解成字符串
params = Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
}
url = params ? url + '?' + params : url;
xhr.open(method, url, true);
xhr.send();
}

//post
if (method === 'post' || method === 'POST') {
xhr.open(method, url, true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(params));
}
});
}


// 用法

ajax('GET' , '127.0.0.1/data.json', {
data:{
name:'www',
age:14,
}
}).then(res=>{
console.log(res);
})