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

区别

相关推荐
guts°2 小时前
17-VRRP
网络·智能路由器
Jewel Q2 小时前
动态路由协议基础
网络·智能路由器
宇称不守恒4.02 小时前
2025暑期—06神经网络-常见网络2
网络·人工智能·神经网络
Dreams_l3 小时前
网络编程2(应用层协议,传输层协议)
运维·服务器·网络
7ACE3 小时前
Wireshark TS | 发送数据超出接收窗口
网络协议·tcp/ip·wireshark
数据与人工智能律师3 小时前
数字迷雾中的安全锚点:解码匿名化与假名化的法律边界与商业价值
大数据·网络·人工智能·云计算·区块链
先知后行。3 小时前
网络协议HTTP、TCP(草稿)
网络·网络协议
xzkyd outpaper3 小时前
QUIC协议如何在UDP基础上解决网络切换问题
网络·计算机网络·udp·quic
碳酸的唐4 小时前
Inception网络架构:深度学习视觉模型的里程碑
网络·深度学习·架构
Jewel Q4 小时前
VRRP技术
网络·智能路由器