封装ajax函数

来源:互联网 发布:细说php第四版pdf下载 编辑:程序博客网 时间:2024/05/21 17:43
//要不要参数//要:传输的方式,路径,数据,回调函数function ajax(method,url,data,fnsuccess){    //1号线:创建ajax对象    var xhr;    if(window.XMLHttpRequest){        xhr=new XMLHttpRequest();    }    else{        xhr=new ActiveXObject('Microsoft.XMLHTTP');    }    //2号线:发送http请求(准备数据,真正的发送)    if(method=='GET' && data){        //如果是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);    }    //4号线:拿到的数据返回给调用ajax函数的地方    xhr.onreadystatechange=function(){        if(xhr.readyState==4){            if(xhr.status==200){                if(fnsuccess){                    fnsuccess(xhr.responseText);//注意这里只能接收字符串,json和html数据。如果传过来的是xml数据格式,要换用responseXML属性                }            }            else{                alert('出差了,出错状态是:'+xhr.status);            }        }    }}