原生JavaScript实现Ajax封装示例

作者:闭包旅人时间:2026-10-28 08:43:08浏览:151

本文分享了一段基于原生JavaScript实现的Ajax封装代码。通过判断浏览器类型(IE或其他)创建XMLHttpRequest对象,分别实现了GET和POST两种请求方式。代码展示了如何处理ActiveXObject兼容性问题、设置请求头以及处理响应数据,并包含了一个简单的DOM操作示例用于演示调用过程。

Ajax封装代码实现

以下是具体的代码实现:

//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();
    };
}
作者最新文章