# 基于promise封装的ajax

function ajax(options) {
  return new Promise((resolve, reject) => {
    if (!options.url) return;

    options.type = options.type || "GET";
    options.timeout = options.timeout || 10000;
    let timer;

    // 1.创建
    let xhr = new XMLHttpRequest();

    if (options.type.toUpperCase() === "GET") {
      // 2.连接
      xhr.open("get", `${options.url}`, true);
      // 3.发送
      xhr.send();
    }

    // 4.接收
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        clearTimeout(timer);
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          resolve(xhr.responseText);
        } else {
          reject(xhr.status);
        }
      }
    };

    if (options.timeout) {
      timer = setTimeout(() => {
        xhr.abort();
        reject("超时");
      }, options.timeout);
    }
  });
}
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
最后更新时间: 3/31/2022, 7:35:08 PM