自己实现ajax封装示例分享_Javascript教程-查字典教程网
自己实现ajax封装示例分享
自己实现ajax封装示例分享
发布时间:2016-12-30 来源:查字典编辑
摘要:复制代码代码如下://javascriptObject:ajaxObject//CreatedByRexLeefunctionAjax(ur...

复制代码 代码如下:

//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 GETn'+a.get())

//alert('by POSTn'+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();

};

}

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新Javascript教程学习
    热门Javascript教程学习
    编程开发子分类