JavaScript AJAX

AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下,与服务器进行异步通信的技术。它允许网页在后台发送和接收数据,从而实现动态更新页面内容。

AJAX的工作原理

  • 用户触发事件(如点击按钮)
  • JavaScript通过XMLHttpRequestFetch API 向服务器发送请求。
  • 服务器处理请求并返回数据(通常是JSON或XML格式)
  • JavaScript解析返回的数据并更新页面内容

核心原理

  • XMLHttpRequest :创建异步请求,通过 open() 设置请求方法(GET/POST)、send() 发送请求。
  • 数据格式 :支持 JSON(轻量级)和 XML(结构化),例如 response = JSON.parse(xhr.responseText)

使用 XMLHttpRequest 实现 AJAX

  1. 创建 XMLHttpRequest 对象。
  2. 使用 open() 方法设置请求类型(GET/POST)和 URL。
  3. 设置 onload 回调函数处理成功响应。
  4. 设置 onerror 回调函数处理错误。
  5. 使用 send() 方法发送请求。
js 复制代码
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);

xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error("Request failed with status:", xhr.status);
  }
};

xhr.onerror = function () {
  console.error("Request failed");//可以不写
};

xhr.send();

使用 Fetch API 实现 AJAX

Fetch API 是现代浏览器提供的更简洁、强大的 AJAX 实现方式。(基于 Promise 的简化请求方式。)

  1. 使用 fetch() 方法发送请求。
  2. 使用 .then() 处理响应并解析 JSON 数据。
  3. 使用 .catch() 处理错误。
js 复制代码
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error("Fetch error:", error);
  });

使用 async/await 简化 Fetch API

async/await 是 ES7 引入的语法糖,可以更简洁地处理异步操作。

  1. 使用 async 声明异步函数。
  2. 使用 await 等待 fetch()response.json() 完成。
  3. 使用 try/catch 处理错误。(可以不写)
js 复制代码
async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Fetch error:", error);
  }
}
fetchData();

发送POST请求

使用 Fetch API 发送 POST 请求

  1. 调用fetch函数
  2. 处理响应(fetch返回一个Promise,表示请求的响应。)
  3. 处理解析后端数据
  4. 错误处理
js 复制代码
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  //请求头
  headers: {
    "Content-Type": "application/json",
  },  
  //请求体
  body: JSON.stringify({
    title: "foo",
    body: "bar",
    userId: 1,
  }),  
})
//fetch返回的响应对象
  .then((response) => response.json())
  //解析后的JSON数据
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.error("Fetch error:", error);
  });

使用XMLHttpRequest发送POST请求

  1. 创建XMLHttpRequest对象
  2. 请求配置
  3. 设置请求头
  4. 处理响应
  5. 处理错误
  6. 发送请求
js 复制代码
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
xhr.setRequestHeader("Content-Type", "application/json");
//"application/json"表示请求体类型
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error("Request failed with status:", xhr.status);
  }
};

xhr.onerror = function () {
  console.error("Request failed");
};

xhr.send(JSON.stringify({
  title: "foo",
  body: "bar",
  userId: 1,
}));

处理JSON数据

JSON是AJAX中最常用的数据格式

解析JSON

js 复制代码
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => {
    console.log(data.title); // 输出: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
  });

生成JSON

js 复制代码
const data = {
  title: "foo",
  body: "bar",
  userId: 1,
};

const jsonString = JSON.stringify(data);
console.log(jsonString); // 输出: {"title":"foo","body":"bar","userId":1}

跨域请求

跨域请求是指请求的资源与当前页面的域名、协议或端口不同。浏览器默认禁止跨域请求,除非服务器设置了 CORS(跨域资源共享)头。

js 复制代码
Access-Control-Allow-Origin: *

使用第三方库(如Axios)

Axios是一个流行的HTTP客户端库,简化了AJAX请求

js 复制代码
axios.get("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error("Axios error:", error);
  });

总结*

  • AJAX:通过 XMLHttpRequestFetch API 实现异步通信。
  • Fetch API:现代、简洁的 AJAX 实现方式,支持 async/await
  • POST 请求:通过设置 methodbody 发送数据。
  • JSON:常用的数据格式,使用 JSON.parse()JSON.stringify() 解析和生成。
  • CORS:处理跨域请求时需要注意服务器配置。
相关推荐
QQ1__81151751521 分钟前
Spring boot名城小区物业管理系统信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·vue.js·spring boot
钛态22 分钟前
前端微前端架构:大项目的救命稻草还是自找麻烦?
前端·vue·react·web
一粒黑子23 分钟前
【实战解析】阿里开源 PageAgent:纯前端 GUI Agent,一行JS让网页支持自然语言操控
前端·javascript·开源
独角鲸网络安全实验室25 分钟前
2026微信小程序抓包全解析:从实操落地到合规风控,解锁前端调试新范式
前端·微信小程序·小程序·抓包·系统代理绕过·https证书严格校验·进程隔离
紫微AI25 分钟前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
GISer_Jing26 分钟前
AI前端(From豆包)
前端·aigc·ai编程
IT枫斗者26 分钟前
前端部署后如何判断“页面是不是最新”?一套可落地的版本检测方案(适配 Vite/Vue/React/任意 SPA)
前端·javascript·vue.js·react.js·架构·bug
测试修炼手册26 分钟前
[测试技术] 深入理解 JSON Web Token (JWT)
前端·json
AI老李28 分钟前
2026 年 Web 前端开发的 8 个趋势!
前端
里欧跑得慢30 分钟前
15. Web可访问性最佳实践:让每个用户都能平等访问
前端·css·flutter·web