用promise封裝ajax操作的例子

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);
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章