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

区别

相关推荐
科技块儿9 小时前
如何使用IP数据云提升网络风控、减少业务欺诈
网络·网络协议·tcp/ip
fei_sun9 小时前
【计网】2025年真题
网络
Fnetlink19 小时前
中小企业网络环境优化与安全建设
网络·安全·web安全
爬山算法10 小时前
Netty(10)Netty的粘包和拆包问题是什么?如何解决它们?
服务器·网络·tcp/ip
Sleepy MargulisItG10 小时前
【Linux网络编程】应用层协议:HTTP协议
linux·服务器·网络·http
bruce_哈哈哈10 小时前
车载网络--soa总结--some/ip等认识
网络
logic_510 小时前
静态路由配置
运维·服务器·网络
门思科技10 小时前
企业级 LoRaWAN 网关远程运维方案对比:VPN 与 NPS FRP 的技术与安全差异分析
运维·网络·安全
kkk_皮蛋11 小时前
RTCP: 统计、同步与网络自适应
网络
suzhou_speeder11 小时前
企业数字化网络稳定运行与智能化管理解决方案
运维·服务器·网络·交换机·poe·poe交换机