AJAX介绍

XMLHttpRequest

get请求使用

javascript 复制代码
const xhr = new XMLHttpRequest();
xhr.open("GET", "/data/test.json", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      alert(xhr.responseText);
    } else {
      console.log("其他情况");
    }
  }
};

xhr.send(null);

post请求

javascript 复制代码
const xhr = new XMLHttpRequest();
xhr.open("POST", "/data/test.json", true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      alert(xhr.responseText);
    } else {
      console.log("其他情况");
    }
  }
};

const postData = {
  userName: "zhangsan",
  password: "xxx",
};

xhr.send(JSON.stringify(postData));

xhr.readyState

用的最多的还是4

xhr.status

手写AJAX

javascript 复制代码
function myAjax(url, method = "GET", data = null, headers = {}) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    for (const [key, value] of Object.entries(headers)) {
      xhr.setRequestHeader(key, value);
    }

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = xhr.responseText
              ? JSON.parse(xhr.responseText)
              : null;
            resolve(response);
          } catch (error) {
            reject(new Error("JSON解析失败"));
          }
        } else {
          const errorMap = {
            400: "请求参数错误",
            401: "未授权",
            403: "禁止访问",
            404: "资源未找到",
            500: "服务器内部错误",
          };
          reject(
            new Error(errorMap[xhr.status] || `请求失败,状态码:${xhr.status}`)
          );
        }
      }
    };
    xhr.send(method.toUpperCase() === "GET" ? null : data);
  });
}

ajax的常见使用

  • 传统 XMLHttpRequest:兼容性好,适合旧项目。

  • Fetch API:现代、简洁,推荐用于新项目。

  • Axios:功能强大,适合企业级应用。

存储

缺点

localStorage和sessionStorage

区别

相关推荐
未来之窗软件服务19 分钟前
SAN 文件编码识别-对抗网络搜索—智能编程—仙盟创梦IDE
网络·ide·文件编码·仙盟创梦ide
蜡笔小新..19 分钟前
【计算机网络01】 网络组成与三种交换方式
网络·计算机网络
大G哥22 分钟前
【WebSocket&IndexedDB】node+WebSocket&IndexedDB开发简易聊天室
网络·websocket·网络协议
Javis21140 分钟前
【Linux高级全栈开发】2.1高性能网络-网络编程——2.1.1 网络IO与IO多路复用——select/poll/epoll
linux·运维·网络
1001101_QIA1 小时前
【QT】UDP通讯本地调试
网络·网络协议·udp
yong15858553431 小时前
[SIGPIPE 错误] 一个 Linux socket 程序,没有任何报错打印直接退出程序
linux·服务器·网络·c++
小陶来咯3 小时前
【高级IO】多路转接之单线程Reactor
服务器·网络·数据库·c++
云攀登者-望正茂7 小时前
AKS 网络深入探究:Kubenet、Azure-CNI 和 Azure-CNI(overlay)
网络·azure
时序数据说7 小时前
IoTDB磁盘I/O性能监控与优化指南
大数据·网络·数据库·时序数据库·iotdb
cocogogogo9 小时前
Jupyter Notebook / Lab 疑难杂症记:从命令找不到到环境冲突与网络阻塞的排查实录
网络·ide·jupyter