1. 基础 AJAX 请求案例 🛠️

使用 XMLHttpRequest 实现简单数据获取:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data', true);
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();
异步请求

2. 使用 Fetch API 的案例 📌

现代浏览器推荐的异步请求方式:

fetch('/api/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('请求失败:', error);
  });
Fetch_API

3. 实际应用场景 📈

  • 📌 动态表单提交:无需刷新页面即可提交表单数据
  • 📌 实时数据更新:如聊天应用、股票行情等
  • 📌 页面局部刷新:提升用户体验
  • 📌 文件上传下载:支持大文件分块传输

了解更多 AJAX 教程,请访问 [/ajax_tutorial]。