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

11次阅读

共计 728 个字符,预计需要花费 2 分钟才能阅读完成。

一般的 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);
    })

正文完
 0