原生AJAX教程

262 阅读2分钟

什么是 AJAX ?

  1. Asynchronous JavaScript and XML(异步的 JavaScriptXML
  2. 是一种用于创建动态网页的技术
  3. 通过与后台进行 HTTP 交互,异步获取数据并进行局部更新

XMLHttpRequest 对象

XMLHttpRequest 对象用于在后台与服务器交换数据
您可以使用它:

  • 在不重新加载页面的情况下更新网页
  • 在页面已加载后从服务器请求数据
  • 在页面已加载后从服务器接收数据
  • 在后台向服务器发送数据

所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。
为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject 对象。

XHR 实例

let xhr;
if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
} else {
    // 兼容IE5 和 IE6
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

XHR 请求

如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open()send() 方法:

xhr.open(method, url, async);
xhr.send(queryString);
方法用法
xhr.open(method, url, async)
  • method:请求的类型;GET 或 POST
  • url:文件在服务器上的位置
  • async:true(异步)或 false(同步)
xhr.send(queryString)仅使用 POST 方法时传值

XHR 响应

获取服务器响应,可通过 XMLHttpRequest 对象的 responseTextresponseXML 属性:

xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
      console.log(xhr.responseXML);
    }
}

readyState 请求的状态

readyState 存放 XHR 的状态信息,从0-4发生变化:

  • 0: 请求未初始化
  • 1: 服务器已建立连接
  • 2: 请求已接收
  • 3: 请求处理中
  • 4: 请求已完成,且响应已完成

status 响应的状态

status 存放 XHR 的响应状态,状态码可由服务器端自行返回。

简单封装

/**
 * 请求参数
 * @param options
 */
function request(options) {
  const { method, url, data, headers } = options;
  let xhr;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    // 兼容IE5、IE6
    xhr = new ActiveXObject('Microsoft.XMLHTTP')
  }
    // 监听readyState改变
  xhr.onreadystatechange = function () {
    // 打印状态码
    switch (xhr.readyState) {
      case 0:
        console.log('请求未初始化');
        break;
      case 1:
        console.log('服务器已建立连接');
        break;
      case 2:
        console.log('请求已接收');
        break;
      case 3:
        console.log('请求处理中');
        break;
      case 4:
        console.log('请求已完成');
        break;
      default:
        break;
    }
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
    }
  }
  xhr.open(method, url, true);
  // xhr.withCredentials = true; // 是否携带cookies
  if (method === 'GET') {
    xhr.send();
  } else {
    // post方法设置请求头,也可以设置自定义请求头
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("userName=admin3&password=123123");
  }
}
request({
  method: 'GET',
  url: 'http://127.0.0.1:7001/api/list'
})