promise封装原生ajax

279 阅读1分钟

封装一个get请求的方法

function getJSON(url) {  
    return new Promise(function(resolve, reject) {
    
        if(window.XMLHttpRequest){//兼容处理
           XHR = new XMLHttpRequest();
       }else{
           xhr = new ActiveXObject("Microsoft.XMLHTTP");   
       }
        
        XHR.open('GET', url, true);  
        XHR.send();  
        //如果用post请求的话需要一个请求头
        XHR.setRequestHeader("Content-Type", "application/x-xxx-form-urlencoded");
        
        XHR.onreadystatechange = function() {  
            if (XHR.readyState == 4) {  
                if (XHR.status == 200) {  
                    try {  
                        var response = JSON.parse(XHR.responseText);  
                        resolve(response);  
                    } catch (e) {  
                        reject(e);  
                    }  
                } else {  
                    reject(new Error(XHR.statusText));  
                }  
            }  
        }  
    })  
}  
  
getJSON(url).then(res => console.log(res));