Ajax兼容处理+发送请求+接收返回信息

针对不同的浏览器,Ajax对象的创建方式也是不同的,对于IE5 IE6 创建AJAX的方式和 IE7 主流浏览器都是不同的.

在创建ajax对象的时候,我们需要做一下兼容处理

老版本IE6,IE5,主流浏览器JAJAX兼容处理

<script>
    function CompatiableAjax(){
                    var obj=null;
                    if(window.ActiveXObject){
                            obj = new ActiveXObject("Microsoft.XMLHTTP");
                    }else{
                            obj = new XMLHttpRequest();
                    }
                    return obj;
            }
            var ajx = CompatiableAjax();
</script>

open(type,addr,method):通过某种放打开一个连接服务器的通道,使用http协议来完成。采用同步或异步的方式 

ajx.open('get','./02.php');

send:post方式打开的连接通道。

get方式发送数据和接收服务器返回数据

        

<script type="text/javascript">
    function CompatiableAjax(){
                    var obj=null;
                    if(window.ActiveXObject){
                            obj = new ActiveXObject("Microsoft.XMLHTTP");
                    }else{
                            obj = new XMLHttpRequest();
                    }
                    return obj;
            }
    function f2(){
        var xmlhttp = CompatiableAjax();
        xmlhttp.open('get','./02.php');
        xmlhttp.send(null);
        //根据ajax状态获取返回数据
        xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState==4 && xmlhttp.status==200){
                    //接收返回数据
                  var messayreturn=xmlhttp.responseText;
            }
        }
    }
</script>

  POST方式发送数据和接收服务器返回数据

 <script type="text/javascript">
            function CompatiableAjax(){
                    var obj=null;
                    if(window.ActiveXObject){
                            obj = new ActiveXObject("Microsoft.XMLHTTP");
                    }else{
                            obj = new XMLHttpRequest();
                    }
                    return obj;
            }
            function f2(){
                var ajx = CompatiableAjax();    
                var usr ="cat";
                var data ="name="+usr;
            //    alert(data);
            
                ajx.open('post','./02.php');
                ajx.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                ajx.send(data);
                ajx.onreadystatechange=function(){
                        if(ajx.readyState==4 && ajx.status ==200){
                        console.log(ajx.responseText);
                        }            
                }    
            }
  </script>

POST发送的数据格式,变量用&符隔开

$data ="name="+alis+"&age="+24;

POST和GET方式可以同时发送。相互之间不影响,即使POST设置了头协议,也跟GET毫无关系。


你可能感兴趣的:(Ajax兼容处理+发送请求+接收返回信息)