您的位置:首页 > 其它

使用AJAX技术实现网页部分信息的更新

2017-03-23 18:39 399 查看
1创建.AJAX对象

主流浏览器:var ajax=new XMLHttpRequest();

IE低版本浏览器:var ajax=new ActiveXObject('Microsoft.XMLHTTP');

2向服务器发送http请求

if(method=='GET' && data){

        url=url+'?'+data;

    }

    xhr.open(method,url,true);

    

    if(method=='GET'){

        xhr.send(null);

    }

    else{

        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

        xhr.send(data);

    }

3获取ajax对象传来的信息,处理后返回给ajax对象

<?php

    $userName=$_GET['name'];

    

    if($userName=='admin'){

        echo '该用户名不能使用';

    }

    else{

        echo '该用户名能使用';

    }

    

?>

4把数据返回给调用ajax对象的地方

xhr.onreadystatechange=function(){

        if(xhr.readyState==4){

            if(xhr.status==200){

                if(fnsuccess){

                    fnsuccess(xhr.responseText);

                }    

            }

            else{

                alert('出差了,出错状态是:'+xhr.status);

            }

        }

    }

把整个过程封装为函数:

function ajax(method,url,data,fnsuccess){

    var xhr;

    if(window.XMLHttpRequest){

        xhr=new XMLHttpRequest();

    }

    else{

        xhr=new ActiveXObject('Microsoft.XMLHTTP');

    }

    if(method=='GET' && data){

        url=url+'?'+data;

    }

    xhr.open(method,url,true);

    if(method=='GET'){

        xhr.send(null);

    }

    else{

        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

        xhr.send(data);

    }

    xhr.onreadystatechange=function(){

        if(xhr.readyState==4){

            if(xhr.status==200){

                if(fnsuccess){

                    fnsuccess(xhr.responseText);

                }

            }

            else{

                alert(xhr.status);

            }

        }

        

    }

}

调用ajax函数

<script type="text/javascript">

            window.onload=function(){

                var oBtn=document.getElementById('btn');

                oBtn.onclick=function(){

                    ajax('GET','aa.txt','',function(str){

                        console.log(str);

                    });

                }

            }

        </script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: