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

来源:互联网 发布:淘宝怎么微信零钱支付 编辑:程序博客网 时间:2024/06/04 23:16

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>

0 0
原创粉丝点击