ajax学习四——封装一个实用的ajax函数

 
 
function ajax(method,url,data,succeed){
    var xhr=null;
    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();
    }else{
        xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
        xhr.send(data);
    }
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            if(xhr.status==200){
                succeed&&succeed(xhr.responseText);
            }else{
                alert("出错了,Err:"+xhr.status);
            }
        }
    }
}



猜你喜欢

转载自blog.csdn.net/tozeroblog/article/details/80722801