//ajax(url,data,type,success,error);
function ajax(json){
if(!json.url){
alert('你是捣乱的');
return
}
json.data=json.data||{};
json.type=json.type||'get';
json.time=json.time||'3000';
var time=null;
if(window.XMLHttpRequest){
var oAjax=new XMLHttpRequest();
}else{
var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
}
switch(json.type.toLowerCase()){
case 'get':
oAjax.open('GET',json.url+'?'+json2Str(json.data),true);
break;
case'post':
oAjax.open('POST',json.url,true);
oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
oAjax.send(json2Str(json.data));
break;
}
oAjax.onreadystatechange=function(){
if(oAjax.readyState==4){
if(oAjax.status>=200&&oAjax.status<300||oAjax.status==304){
json.success&&json.success(oAjax.responseText);//成功后返回的文本
}else{
json.error&&json.error(oAjax.status);
}
clearTimeout(timer);
}
};
timer=setTimeout(function(){
alert('服务器超时了');
oAjax.onreadystatechange=null;
},json.time);
}
function json2Str(json){
json.t=Math.random();
var arr=[];
for(var name in json){
arr.push(name+'='+json[name]);
}
return arr.join('&')
}
网友评论