用promise封装ajax操作的例子

来源:互联网 发布:江苏省网络作家协会 编辑:程序博客网 时间:2024/06/04 23:33
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("/posts.json").then(function (json) {    console.log('Contents: '+json);},function (error) {    console.log('出错了 ', error);})
原创粉丝点击