学习链接

阮一峰:XMLHttpRequest 对象

实现AJAX请求

Ajax

  • 创建 XMLHttpRequest 实例

  • 发出 HTTP 请求

  • 接收服务器传回的数据

  • 更新网页数据

  1. function ajax({ url = null, method = 'GET', type = 'json', async = true }) {
  2. return new Promise((resolve, reject) => {
  3. const xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  4. xhr.open(method, url, async)
  5. xhr.responseType = type
  6. xhr.setRequestHeader('Accept', 'application/json');
  7. xhr.onreadystatechange = function () {
  8. if (this.readyState !== 4) {
  9. return;
  10. }
  11. if (this.status === 200 || this.status === 304) {
  12. resolve(this.responseText);
  13. } else {
  14. reject(this.statusText);
  15. }
  16. }
  17. xhr.onerror = err => {
  18. reject(err);
  19. }
  20. xhr.send(null);
  21. })
  22. }