AJAX 原理和实现

1. 什么是 AJAX

AJAX 全称 Async JavaScript and XML,即异步的 JavaScript 与 XML,是一种创建交互式网页应用的网页开发技术。它可以在不重新加载整个网页的情况下,与服务器交换数据,并更新部分网页。

AJAX 的原理简单来说就是:通过 XMLHttpRequest 对象向服务器发异步请求,从服务器获得数据,然后用 JavaScript 操作 DOM 来更新页面。

2. 实现过程

const xhr = new XMLHttpRequest();
xhr.open('get', url, true);  // 第三个参数 true 表示异步
xhr.send();                   // GET 请求 send() 不带 body;POST 可传 body

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300) {
      console.log(xhr.responseText);
      console.log(xhr.response);
    } else if (xhr.status >= 400) {
      console.log('错误: ' + xhr.statusText);
    }
  }
};

readyState 取值:0 = 未初始化,1 = open 已调用,2 = send 已调用,3 = 接收中,4 = 完成。

3. 封装 AJAX

function ajax(options) {
  const xhr = new XMLHttpRequest();
  options = options || {};
  options.type = (options.type || 'GET').toUpperCase();
  options.dataType = options.dataType || 'json';
  const params = options.data;

  if (options.type === 'GET') {
    xhr.open(options.type, options.url + '?' + options.data);
    xhr.send();
  } else if (options.type === 'POST') {
    xhr.open(options.type, options.url);
    xhr.send(params);
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      const status = xhr.status;
      if (status >= 200 && status < 300) {
        options.success && options.success(xhr.responseText, xhr.responseXML);
      } else {
        options.fail && options.fail(status);
      }
    }
  };
}

补充:现代前端几乎都用 fetch 或 axios 替代原生 XHR,它们返回 Promise、支持拦截器、请求/响应转换、自动 JSON 解析等,使用上比 XHR 简洁很多。XHR 主要用于需要支持上传进度、responseType='blob' 等少数场景。

来源整理自:vue3js.cn 面试官系列