AJAX

AJAX是什么?

AJAX是Asynchronous JavaScript and XML 的简称,是一项允许JavaScript脚本向服务器发送HTTP请求,能够在不刷新页面的情况下获取后端数据的技术。AJAX不是一项新技术,而是许多成熟技术的集合。

AJAX技术包括:

  1. HTML
  2. CSS
  3. JavaScript
  4. The Document Object Model
  5. XML、XSLT、JSON(数据传输方式)
  6. XMLHttpRequest Object(AJAX核心对象)

AJAX的实现(四个步骤)

// 1 创建ajax核心对象
const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
// 2 打开链接
xhr.open(
  "get",
  "https://www.fastmock.site/mock/01811b5c80dcd90570734587f22b934c/students/getStudents",
  strue
);
// 3 发送(post请求时,数据放在请求体中--即send方法括号内)
xhr.send();
// 4 监听请求状态,接收数据
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const data = xhr.responseText;
    const result = JSON.parse(data);
    // 处理数据
    。。。
  }
};

封装AJAX

考虑因素:

  • 需要传入的参数,使用对象解构参数形式方便传参
  • 使用不同的方法get/post请求时,携带数据的位置不同
  • 传输的数据为字符串的键值对形式,如:name=zs&age=18
// 参数(请求类型、地址、是否异步、请求携带的数据、处理数据的回调)
const ajax = ({ type = "get", url, async = true, data = "", success }) => {
  const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
  if (typeof data === "object") {
    data = toStr(data);
  }
  if (type.toLowerCase === "get") {
    xhr.open(type, url + "?" + data, async);
    xhr.send();
  } else {
    xhr.open(type, url, async);
    xhr.send(data);
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      const data = xhr.responseText;
      const result = JSON.parse(data);
      success(result);
    }
  };
};

// 将对象转为字符串的键值对形式:name=zs&age=18
function toStr(obj) {
  let str = "";
  for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
      const value = obj[key];
      str += `&${key}=${value}`;
    }
  }
  str = str.substring(1);
  return str;
}

// 调用
ajax({
  url:"https://www.fastmock.site/mock/01811b5c80dcd90570734587f22b934c/students/getStudents",
  data: { name: "zs", age: 18 },
  success(result) {
    stusList.innerHTML = result.stus
      .map((v) => {
        return `<tr>
          <td>${v.id}</td>
          <td>${v.name}</td>
          <td>${v.age}</td>
          <td>${v.gender}</td>
          <td>${v.address}</td>
          </tr>
        `;
      }).join("");
  },
});
原文地址:https://www.cnblogs.com/Lotus3904/p/14385853.html