展会信息港展会大全

ajax封装示例代码
来源:互联网   发布日期:2016-01-26 10:22:06   浏览:1997次  

导读:这篇文章主要介绍了自己实现ajax封装示例,需要的朋友可以参考下代码如下: javascript Object: ajax Object Created By RexLeefunction Ajax(url,data){ this url=url; this data=data; this br ...

这篇文章主要介绍了自己实现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();

};

}

赞助本站

人工智能实验室

相关热词: 封装 ajax

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港