利用promise封装ajax

1.网上不少封装,可是本身以为为何要分开封装呢?get和post封装成一个函数很差么?根据本身之前封装的ajax顺手改了一下,并在本身的项目中使用了一下,还能够。

function _ajax(options) {
  // body...
  try {
    // statements
    options = options || {};
    return new Promise((resolve, reject) => {
      let xhr;
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
      } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
      }
      if (options.type.toLowerCase() === 'get') {
        options.url = options.url + '?' + params(options.data);
        options.data = null;
      } else {
        options.data = params(options.data);
      }
      xhr.open(options.type, options.url);

      if (options.type.toLowerCase() === 'post') {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      }
      xhr.send(options.data);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status === 200 || xhr.status === 304) {
            let data = xhr.responseText;
            resolve.call(undefined, data);
          } else {
            reject.call(undefined, xhr.status);
          }
        }
      }
    })
  } catch (e) {
    // statements
    console.log(e);
  }

}
复制代码

2.使用方式

_ajax({
    type: 'post',
    url: baseURL + 'url',
    data: {
      method: 'method',
      accessToken: options.accessToken,
      product_id: options.id,
      product_code: options.code,
      price: options.price
    }
  }).then(function (res) {
    console.log(res);
  }, function (err) {
    console.log(err);
  });
复制代码
相关文章
相关标签/搜索