美文网首页
ES6 Promise对象实现的Ajax操作的例子。

ES6 Promise对象实现的Ajax操作的例子。

作者: codeice | 来源:发表于2016-11-17 15:35 被阅读1459次
var getJSON = function(url) {
  var promise = new Promise(function(resolve, reject){
    var client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();

    function handler() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
  });

  return promise;
};

getJSON("http://rap.taobao.org/mockjs/9768/Rap/get").then(function(response) {
  console.log('Contents: ',response);
}, function(error) {
  console.error('出错了', error);
});

相关文章

网友评论

      本文标题:ES6 Promise对象实现的Ajax操作的例子。

      本文链接:https://www.haomeiwen.com/subject/pwidpttx.html