原生js封装ajax的函数(运用promise的回调函数)

//原生ajaxd的post请求模式
//预设ajax中的传输方式(post/get),地址,数据,传输形式
function ajax(methods,url,data,dataType){
    return new Promise((resolve,reject)=>{ //使用promise方式 
        var xhr=window.XMLHttpRequest?
        new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        //判断当前浏览器是否为ie
        xhr.open(methods,url,true);//设置open的内容,第三个参数是是否打开异步,默认不填也是true(异步)
        if(methods=="post"){//如果当前用户用得到是post方式传递数据则需要添加请求头
            xhr.setRequestHeader(
                "Content-Type", "application/x-www-form-urlencoded");
        }
        
    var data2='';
    for(var i in data) {//设置当前传递的数据改为字符串形式传递给后端
            data2+=i+"="+data[i]+"&";
        }
        data2=data2.slice(0,data2.length-1)   //删除改字符串的最后一个&字符
        xhr.onreadystatechange=()=>{
            if(xhr.readyState==4){//判断当前的状态值
                if(xhr.status==200){
                    if(dataType=="json"){//判断当前是否需要传递json的值
                        resolve(JSON.parse(xhr.responseText))
                    }else{
                        resolve(xhr.responseText)
                    }
                   
                }else{
                    reject("请求出错:"+xhr.status)
                }
            }
        }
        xhr.send(data2);
    })
}
var data={
    uname:"gfz",
    upwd:123
    }; 
dataType="json";

ajax("post","login2.php",data,"text").then(function(data){//返回resolve
    console.log(data)
}).catch(function(data){//错误返回reject
    console.log(data)
});








php可以看下这个

 

你可能感兴趣的:(原生js封装ajax的函数(运用promise的回调函数))