关于前端:普通的ajax请求和使用promise的ajax请求

一般的ajax申请:

    //创立一个对象
    let xhr = new XMLHttpRequest();
    //申明申请的形式和门路
    xhr.open('get',url);
    //发送申请
    xhr.send();
    
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            console.log(JSON.parse(xhr.responseText));        
        }
    }

应用promise的ajax申请:

    let getJSON = fucntion(url){
        let promise = new Promise(function(resolve,reject){
            let 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('url').then(function(){
        console.log('内容是:' + json);
    },function(){
        console.log('出错了',err);
    })

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理