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

区别

相关推荐
2503_9248068538 分钟前
海外IP的适用业务范围
网络·网络协议·tcp/ip
Hello.Reader1 小时前
Flink State V2 实战从同步到异步的跃迁
网络·windows·flink
mobai71 小时前
华为NetEngine 8000 M1A路由器配置
网络·华为·智能路由器
-快乐的程序员-1 小时前
simple websocket用法
网络·websocket·网络协议
想不明白的过度思考者2 小时前
JavaEE初阶——中秋特辑:网络编程送祝福从 Socket 基础到 TCP/UDP 实战
网络·tcp/ip·udp·java-ee
半桔2 小时前
【网络编程】网络通信基石:从局域网到跨网段通信原理探秘
linux·运维·网络协议·php
nightunderblackcat2 小时前
四大名著智能可视化推演平台
前端·网络·爬虫·python·状态模式
沐浴露z3 小时前
【深入理解计算机网路07】详解局域网:以太网、VLAN与无线局域网
网络·网络协议·计算机网络·408
二川bro4 小时前
第28节:网络同步与多人在线3D场景
网络·3d
寒月霜华4 小时前
java-网络编程-UDP,TCP通信
java·网络·tcp/ip·udp