Web前端笔试整理13 promise封装ajax

HTML5的Web存储对象有两个,分别是

  • localStorage
  • sessionStorage

Http请求返回码(status code)中,代表【未授权的请求】的代码是

401

CSS3中,能使用div的宽度变化有2秒的过度效果的属性是

transition

描述一下脚本<script>放在和放到底部的区别

放<head>中的情况:脚本会优先加载,但加载过程中,还没加载完,会使脚本访问不到中的元素。

放底部:脚本在加载后加载,能够保证脚本有效地访问元素。

例外情况:脚本中没有访问元素的情况下,两种加载方式效果一致。

使用Promise封装Ajax操作

原始的Ajax操作如下:

var onSuccess = function (result) {}; // 成功的回调
var onFail = function (error) {}; // 失败的回调
var req = new XMLHttpRequest();
req.open("POST", "www.baidu.com", true);
req.onload = function () {
  if (req.readyState === 4 && req.status === 200) {
    onSuccess(req.response);
  } else {
    onFail(req.statusText);
  }
};
req.onerror = function () {
  onFail(Error("网络异常"));
};

封装后:

// ajax函数的默认参数
var ajaxOptions = {
  url: "#",
  method: "GET",
  async: true,
  timeout: 0,
  data: null,
  dataType: "text",
  headers: {},
  onprogress: function () {},
  onuploadprogress: function () {},
  xhr: null,
};
// 使用Promise封装
function ajax(optionsOverride) {
  // 将传入的参数与默认设置合并
  var options = {};
  for (var k in ajaxOptions) {
    options[k] = optionsOverride[k] || ajaxOptions[k];
  }
  options.async = opsiotn.async === false ? false : true;
  var xhr = (options.xhr = options || new XMLHttpRequest());
  return new Promise(function (resolve, reject) {
    xhr.open(options.method, options.url, options.async);
    xhr.timeout = opstions.timeout;
    // 设置请求头
    for (var k in opstions.headers) {
      xhr.setRequestHeader(k, opstions.headers[k]);
    }
    // 注册xhr对象事件
    xhr.onprogress = options.onprogress;
    xhr.upload.onprogress = opstions.onuploadprogress;
    xhr.responseType = options.dataType;
    xhr.onabort = function () {
      reject(
        new Error({
          errorType: "abort_error",
          xhr: xhr,
        })
      );
    };
    xhr.ontimeout = function () {
      reject({
        errorType: "timeout_error",
        xhr: xhr,
      });
    };
    xhr.onloadend = function () {
      if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)
        resolve(xhr);
      else {
        reject({
          errorType: "status_error",
          xhr: xhr,
        });
      }
    };
    try {
      xhr.send(options.data);
    } catch (e) {
      reject({
        errorType: "send_error",
        error: e,
      });
    }
  });
}
// 使用
ajax({
  url: "http://localhost:3000/suc",
  async: true,
  onprogress: function (evt) {
    console.log(evt.position / evt.total);
  },
  dataType: "text/json",
}).then(
  function (xhr) {
    console.log(xhr.response.name);
  },
  function (e) {
    console.log(JSON.stringify(e));
  }
);
原文地址:https://www.cnblogs.com/xiaoxu-xmy/p/13712280.html