使用Promise封装原生Ajax方法--get-post


class myAjax {
  // 封装 GET 请求
  static get(url) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.timeout = 5000; // 设置超时时间为 5 秒
      // 设置响应的回调
      xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText); // 直接解析响应
            resolve(response);
          } catch (e) {
            reject(`Error parsing JSON: ${e.message}`);
          }
        } else {
          reject(`Error: ${xhr.status} - ${xhr.statusText}`); // 请求失败,返回错误信息
        }
      };
      // 设置请求出错的回调
      xhr.onerror = function () {
        reject("Network error or request failed"); // 网络错误,返回具体错误信息
      };
      // 设置超时错误处理
      xhr.ontimeout = function () {
        reject("Request timed out");
      };
      // 发送请求
      xhr.send();
    });
  }

  // 封装 POST 请求
  static post(url, data) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-Type", "application/json"); // 设置请求头
      xhr.timeout = 5000; // 设置超时时间为 5 秒
      // 设置响应的回调
      xhr.onload = function () {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText); // 直接解析响应
            resolve(response);
          } catch (e) {
            reject(`Error parsing JSON: ${e.message}`);
          }
        } else {
          reject(`Error: ${xhr.status} - ${xhr.statusText}`); // 请求失败,返回错误信息
        }
      };
      // 设置请求出错的回调
      xhr.onerror = function () {
        reject("Network error or request failed"); // 网络错误,返回具体错误信息
      };
      // 设置超时错误处理
      xhr.ontimeout = function () {
        reject("Request timed out");
      };
      // 发送 POST 请求,数据作为 JSON 字符串传递
      xhr.send(JSON.stringify(data));
    });
  }
}

// 使用示例:
const username = "octocat"; // 你想查询的 GitHub 用户名
myAjax
  .get(`https://api.github.com/users/${username}`)
  .then((response) => {
    console.log("GitHub user response:", response); // 打印 GitHub 用户数据
  })
  .catch((error) => {
    console.error("GitHub request failed:", error);
  });

const postData = {
  title: "foo",
  body: "bar",
  userId: 1,
};

myAjax
  .post("https://jsonplaceholder.typicode.com/posts", postData)
  .then((response) => {
    console.log("POST response:", response); // 打印 POST 请求的响应数据(已经是 JSON)
  })
  .catch((error) => {
    console.error("POST request failed:", error);
  });


posted @ 2025-04-18 14:49  苏沐~  阅读(31)  评论(0)    收藏  举报