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

区别

相关推荐
Demisse2 小时前
[华为eNSP] OSPF综合实验
网络·华为
工控小楠2 小时前
DeviceNet转Modbus TCP网关的远程遥控接收端连接研究
网络·网络协议·devicenet·profient
搬码临时工2 小时前
电脑同时连接内网和外网的方法,附外网连接局域网的操作设置
运维·服务器·网络
安全系统学习3 小时前
【网络安全】Qt免杀样本分析
java·网络·安全·web安全·系统安全
逃逸线LOF4 小时前
Spring Boot论文翻译防丢失 From船长&cap
网络
计算机毕设定制辅导-无忧学长4 小时前
从 AMQP 到 RabbitMQ:核心组件设计与工作原理(二)
网络·rabbitmq·ruby
midsummer_woo4 小时前
【2025年】解决Burpsuite抓不到https包的问题
网络协议·http·https
光芒Shine5 小时前
【物联网-TCP/IP】
网络·网络协议·tcp/ip
小白杨树树7 小时前
【WebSocket】SpringBoot项目中使用WebSocket
spring boot·websocket·网络协议
云计算-Security7 小时前
如何理解 IP 数据报中的 TTL?
网络协议·tcp/ip