XMLHttpRequest 与 Ajax 概要

  关于XMLHttpRequest

开发者使用XMLHttpRequest对象与服务端进行交互(发送http请求、接受返回数据等),可以在不打断用户下一步操作的情况下刷新局部页面。XMLHttpRequest在Ajax中被大量使用。

  XMLHttpRequest被应用时的处理机制

  (图片来源:developer.mozilla.org)

  关于Ajax

Ajax(切勿读为汉语化的“阿贾克斯”,应读英音/ˈeɪˌdʒæks/--“A寨科泗”。。)全称:Asynchronous JavaScript And XML (异步的JavaScript和XML)。

Ajax不仅可以只更新页面中的部分DOM,而且工作流程是异步的,不会阻塞其后面代码的正常执行。

在现代Web标准和实际应用中,Ajax正在逐步地被一些JavaScript框架封装好的方法和官方新的 Fetch API 所替代。

在正式介绍Ajax的使用前,我们认识下IE中的一个与XMLHttpRequest对象相应的概念(尽管后续它不会再被提及):

var ajax = new ActiveXObject('Microsoft.XMLHTTP'); 

  深入了解XMLHttpRequest

// xhr对象的构造函数,用来实例化一个xhr对象。
XMLHttpRequest()
// xhr的常用属性

/* 1. onreadystatechange属性将指向一个事件处理函数,当xhr的readyState属性发生变化时被触发 */
xhr.onreadystatechange
// usage:
xhr.onreadystatechange = callback;

/* 2. --ReadOnly-- readyState属性将返回当前请求的状态 */
xhr.readyState

// usage:
const xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); // readyState will be 0

xhr.open('GET', '/api', true);
console.log('OPENED', xhr.readyState); // readyState will be 1

xhr.onprogress = function () {
    console.log('LOADING', xhr.readyState); // readyState will be 3
};

xhr.onload = function () {
    console.log('DONE', xhr.readyState); // readyState will be 4
};

xhr.send();

// 具体示意如下图(插播一条广告):

/* 3. 获取或设置responseType(符合XMLHttpRequestResponseType规范的字符串) */
xhr.responseType

// usage:
const resType = xhr.responseType;
// or
xhr.responseType = 'json';

// XMLHttpRequestResponseType具体如下(插播第二条广告):

/* 4. --ReadOnly-- response返回响应体所包含的内容,内容格式由responseType决定 */
xhr.response

// usage:
const result = xhr.response;

// 注:在responseType为''或者'text'时,response 和 responseText 可以相互替用

/* 5. --ReadOnly-- status属性将返回数字类型的http状态码 */
xhr.status

// usage:
const status = xhr.status;

/* 6. --ReadOnly-- statusText将返回响应状态的文本描述,分别有''、'OK'、'Not Found' */
xhr.statusText

// usage:
const statusText = xhr.statusText;


/* 7. timeout属性将指定请求自动终止的毫秒数,默认为零,即没有超时设置 */
xhr.timeout

// usage:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api', true);

xhr.timeout = 5000;

xhr.onload = function () { // Request finished. };

xhr.ontimeout = function (e) {
  // when XMLHttpRequest timed out ...
};

xhr.send();
// xhr 的常用方法

/* 1. open 方法将创建一个新的http请求或者重新发送一个已有请求 */
xhr.open(method, url [, async, username, password])

// usage:
xhr.open('GET', '/api');


/* 2. send 方法将向服务器发送一个请求 */
xhr.send(body)

// usage:
xhr.send();


/* 3. abort 方法将退出一个已有请求 */
xhr.abort()

// usage:
xhr.abort();


/* 4. XMLHttpRequestEventTarget.onload (注:不是xhr的方法,而是事件)*/
xhr.onload

// usage:
xhr.onload = callback;


/* 5. setRequestHeader 可以设置一个http请求头的值 */
xhr.setRequestHeader(headername, value)

// usage:
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() { //... };

xhr.send("foo=bar&lorem=ipsum");

  实际编程中Ajax和XMLHttpRequest的应用

// 简单示例
const XHR = new XMLHttpRequest();
const handleReadyStateChange = () => {
  try {
    if (XHR.readyState === XHR.DONE) {
      if (XHR.status === 200) {
        console.log(XHR.response);
      } else {
        throw new Error('request failed!');
      }
    }
  } catch (ex) {
    console.error('Caught Exception: ' + ex.message);
  }
};

function generateRequest(type, api, body = null) {
  if (!XHR) {
    console.error('Cannot find XMLHttpRequest object!');
    return false;  
  }  
  
  XHR.onreadystatechange = handleReadyStateChange;
  XHR.open(type, api);
  XHR.send(body);
}

-- 待续

猜你喜欢

转载自www.cnblogs.com/fanqshun/p/10570642.html