javascript ajax 完整实现代码案例

javascript | 2019-09-13 10:02:39

几乎每次做项目都要用到ajax,如果没有使用jquery或者extjs这样的框架,就需要自己写ajax代码。每次我都把这个代码复制到项目中作为公用代码。一般也不喜欢用jquery或者extjs这样的框架。
那就自己写ajax吧。我一直都把这段代码保存着,每次用都直接复制,先在分享出来,大家一起使用。

function talktoServer(url){
        var req=newXMLHTTPRequst(); 
        var callbackHandler=getReadyStateHandler(req);
        req.onreadystatechange=callbackHandler;
        req.open("POST",url,true); 
        req.setRequestHeader("Content-Type","application/json");
        req.send("msg=houyong"); 
} 
 //创建XMLHTTP对象
function newXMLHTTPRequst(){
        var xmlreq=false; 
        if(window.XMLHttpRequest){
                xmlreq=new XMLHttpRequest();
        }else if(window.ActiveXobject){
                try{ 
                        xmlreq=newActiveXObject("Msxm12.XMLHTTP");
                 }catch(e1){
                         try
                        { 
                                xmlreq=new
                                ActiveXObject("Microsoft.XMLHTTP");
                        }catch(e2){
                        
                        }
                 } 
         } 
        return xmlreq; 
} 
//服务器回调函数
function getReadyStateHandler(req)
{
        return function(){ 
                if(req.readyState==4){
                        if(req.status==200){ 
                        document.getElementById("houyong").innerHTML=req.responseText;
                                 //varmsg_display=document.getElementById("msg_display"); 
                                //msg_display.innerHTML=req.responseText;
                        }else{ 
                                //varhellomsg=document.getElementById("hellomsg");
                                //hellomsg.innerHTML="ERROR"+req.status; 
                         } 
                }
        }
}


登录后即可回复 登录 | 注册
    
关注编程学问公众号