AJAX简介

341 阅读1分钟

一、本质

使用 js 提供的 XMLHttpRequest()

二、AJAX 四部曲

// 实例化
let xhr = null;
if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest(); // 标准创建
} else {
    xhr = new ActiveXObject("Microsoft.XMLHttp");
}
// 绑定监听事件
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        const result = JSON.parse(xhr.responseText);
    }
};
// post请求需要添加请求头消息
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 打开链接
xhr.open("get", "http://www.unkonw.com", true); // 请求方法,请求路径,是否异步
// 发送请求
xhr.send(); // post请求的请求数据放在这里

说明

readyState 请求状态:

  • 0:请求尚未初始化
  • 1:打开服务器连接,发送请求
  • 2:接受消息头信息
  • 3:接收响应主体
  • 4:接受响应完成