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

区别

相关推荐
THMOM9141 分钟前
TinyWebserver学习(9)-HTTP
网络协议·学习·http
D-海漠1 小时前
Modbus_TCP_V4 客户端
网络
虚!!!看代码2 小时前
【Sentinel学习】
网络·sentinel
liulilittle2 小时前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
网硕互联的小客服2 小时前
服务器如何配置防火墙规则以阻止恶意流量和DDoS攻击?
服务器·网络·ddos
Qiq9222 小时前
怎么分析内网ipv6和ipv4流量占比?
网络
数通Dinner2 小时前
P/A初始化协商
网络
网安小白的进阶之路2 小时前
A模块 系统与网络安全 第三门课 网络通信原理-3
网络·windows·安全·web安全·系统安全
HumanRisk2 小时前
HumanRisk-自动化安全意识与合规教育平台方案
网络·安全·web安全·网络安全意识教育