您好,欢迎访问一九零五行业门户网

自己实现ajax封装示例分享_javascript技巧

复制代码 代码如下:
//javascript object: ajax object
//created by rexlee
function ajax(url,data){
    this.url=url;
    this.data=data;
    this.browser=(function(){  
        if(navigator.useragent.indexof(msie)>0) {  
            return msie;//ie浏览器
        }else{
            return other;//其他
    }})();
};
ajax.prototype={
    get:function(){
        var result;
        var xmlhttp;
        if(this.browser=='msie'){
            try{
                xmlhttp=new activexobject('microsoft.xmlhttp');
                }catch(e){
                    xmlhttp=new activexobject('msxml2.xmlhttp');
                    }
            }else{
                xmlhttp=new xmlhttprequest();
            };
        xmlhttp.onreadystatechange=function(){
            result = xmlhttp.responsetext;//闭包,不能采用this.属性
        };
        xmlhttp.open('get',this.url+'?'+this.data,false);//true无法抓取数据,why?
        xmlhttp.send(null);
        return result;
    },
    post:function(){
        var result;
        var xmlhttp;
        if(this.browser=='msie'){
            xmlhttp=new activexobject('microsoft.xmlhttp');
            }else{
                xmlhttp=new xmlhttprequest();
            };
        xmlhttp.onreadystatechange=function(){
            result = xmlhttp.responsetext;//闭包,不能采用this.属性
        };
        xmlhttp.open('post',this.url,false);//需设为false,否则无法抓取responsetext
        xmlhttp.setrequestheader(content-type,application/x-www-form-urlencoded);//post中,这句必须
        xmlhttp.send(this.data);
        return result;
    }
};
//var a=new ajax('opp2.js','');
//alert('by get\\n'+a.get())
//alert('by post\\n'+a.post());
///////////////////////////////
window.onload=function(){
document.getelementbyid(btn).onclick=function(){
    var p=document.getelementbyid(t).value;
    var a=new ajax(phpoop/getpage.php,page=+p);
    document.getelementbyid(box).innerhtml=a.get();
    };
}
其它类似信息

推荐信息