当前位置: 首页 > news >正文

AJAX介绍

XMLHttpRequest

get请求使用

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请求

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

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:功能强大,适合企业级应用。

存储

cookie

 缺点

localStorage和sessionStorage

区别

相关文章:

  • 2024 年 MySQL 8.0.40 安装配置、Workbench汉化教程最简易(保姆级)
  • c++ std::bind、std::bind_front使用笔记
  • CSS—元素水平居中:2分钟掌握常用的水平居中
  • alpine linux 系统最新版安装及使用教程
  • 汇编前置知识学习 第11-13天
  • 【文献阅读】A Survey on Hardware Accelerators for Large Language Models
  • 关联封号率降70%!2025最新IP隔离方案实操手册
  • SQLAlchemy系列教程:基本数据类型及自定义类型
  • Apache Kafka单节点极速部署指南:10分钟搭建开发单节点环境
  • 物联网系统中,多个感知设备采集的数据通过数据终端打包
  • 初始网络编程
  • 【C++设计模式】第四篇:建造者模式(Builder)
  • Android14 串口控制是能wifi adb实现简介
  • SQLAlchemy系列教程:理解SQLAlchemy元数据
  • 【AI深度学习基础】NumPy完全指南终极篇:核心功能与工程实践(含完整代码)
  • 论文阅读和代码实现EfficientDet(BiFPN)
  • 探索 Hutool - JSON:高效的 JSON 处理利器
  • DeepSeek:全栈开发者视角下的AI革命者
  • 【2025rust笔记】超详细,小白,rust基本语法
  • 数据结构第五节:排序
  • 网站制作怎么做搜索栏/武汉网站推广优化
  • 做网站应该了解什么/app推广平台
  • 中国住建部和城乡建设部官网/苏州手机关键词优化
  • 佛山网站建设网站制作公司/网站推广的目的
  • 怎么创建一个平台/外包优化网站
  • 医疗网站前置审批/网络营销服务的特点