简单的ajax连接库分享(不用jquery的ajax)
简单的ajax连接库分享(不用jquery的ajax)
发布时间:2016-12-30 来源:查字典编辑
摘要:复制代码代码如下:varajax={init:function(){varxmlHttp=newXMLHttpRequest();if(!w...

复制代码 代码如下:

var ajax = {

init : function(){

var xmlHttp = new XMLHttpRequest();

if (!window.XMLHttpRequest)

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

return xmlHttp;

},

call : function(opt){

var xmlHttp = this.init();

xmlHttp.onreadystatechange = function(){

if(xmlHttp.readyState===4)

{

xmlHttp.status===200 ?

opt.success(xmlHttp.responseText,xmlHttp.responseXML) : opt.error(xmlHttp.responseText,xmlHttp.status);

}

}

opt.data = this.parseData(opt.data);

if(opt.method.toLowerCase() === 'get'){

opt.url = opt.url + "?" + opt.data;

opt.data = null;

}

xmlHttp.open(opt.method,opt.url,opt.async);

if(opt.method.toLowerCase() === 'post')

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttp.send(opt.data);

},

parseData : function(data){

if(typeof data == 'object'){

var str = '';

for(var i in data){

str += "&"+i+"="+encodeURIComponent(data[i]);

}

return str.length==0 ? str : str.substring(1);

}else{

return data;

}

}

}

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