简单的ajax连接库分享(不用jquery的ajax)
更新时间:2014年01月19日 14:53:33 作者:
自己写了一个简单的ajax连接库,没有使用jquery的ajax,这个代码要比jquery轻量,大家参考使用吧,
复制代码 代码如下:
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中indexOf()和lastIndexOf应用方法实例
这篇文章主要介绍了JavaScript中的indexOf()和lastIndexOf()方法使用实例,是JS入门学习中的基础知识,有需要的朋友可以参考下。2016-08-08
javascript instanceof 与typeof使用说明
instanceof和typeof都能用来判断一个变量是否为空或是什么类型的变量。2010-01-01


最新评论