原生js--ajax异步请求

function request(methodName, params){
    // console.log('methodName--params=='+methodName+"--"+JSON.stringify(params));
    var xmlHttp;
    function GetXmlHttpObject(){
        if (window.XMLHttpRequest){
            // code for IE7+, Firefox, Chrome, Opera, Safari 
            xmlHttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xmlHttp;
    } 
    // -----------ajax方法-----------// 
    function getLabelsPost(){ 
        xmlHttp=GetXmlHttpObject(); 
        if (xmlHttp==null){ 
            alert('您的浏览器不支持AJAX!'); 
            return; 
        }
        xmlHttp.open("POST",requestUrl,true); 
        xmlHttp.setRequestHeader("content-type","application/json"); 
        xmlHttp.send(JSON.stringify(params)); 
        xmlHttp.onreadystatechange=getOkPost;//发送事件后,收到信息了调用函数
    } 
    function getOkPost(){
        if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){ 
            // 本地提示:加载中/处理中 
        } 
        if (xmlHttp.readyState==4 && xmlHttp.status==200){ 
            var data=JSON.parse(xmlHttp.responseText); // 返回值 
            // 处理返回值 
            // console.log(data);
            if (data.success){

            } else {

            }
        }
    }
    getLabelsPost();
}

request('接口方法名','请求参数[object]');

猜你喜欢

转载自blog.csdn.net/weixin_33275327/article/details/81743019