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

区别

相关推荐
せいしゅん青春之我30 分钟前
【JavaEE初阶】1124网络原理
网络·网络协议·java-ee
ONE_SIX_MIX43 分钟前
Debian 的 网络管理器 被意外卸载,修复过程
服务器·网络·debian
liulilittle1 小时前
国际带宽增长与用户体验下降的悖论
网络·网络协议·信息与通信·ip·ux·带宽·通信
shaominjin1232 小时前
Android 约束布局(ConstraintLayout)的权重机制:用法与对比解析
android·网络
江湖人称小鱼哥4 小时前
WSL + Docker 网络访问详解
网络·docker·容器·wsl
六点半8885 小时前
【计算机网络】初识HTTP(超文本传输协议)
网络协议·计算机网络·http
☆璇5 小时前
【Linux】Socket编程UDP
linux·网络·udp
南一Nanyi5 小时前
才知道 DNS 还能基于 HTTPS 实现!
网络协议·安全·面试
_星辰大海乀5 小时前
网络原理 -- HTTP
java·服务器·http·get方法·post方法
真正的醒悟6 小时前
什么是网络割接
运维·服务器·网络