function objToStr(data){
var arr=[];
for(var key in data){
// url中不能出现中文所以需要进行编码
arr.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
// name=lihua
}
// arr=[name=ll,isbn=1]
return arr.join("&");
// return name=ll&isbn=1
}
var ajax=function(obj){
var str=objToStr(obj.data);
var xmlHttp,timer;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
// IE5 IE6兼容
xmlHttp=new ActiveXObject();
}
if(obj.method.toUpperCase()=="GET"){
xmlHttp.open(obj.method,obj.url+"?"+str,true);
xmlHttp.send();
}else{
// console.log(str);
xmlHttp.open(obj.method,obj.url,true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send(str);
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
clearInterval(timer);
if(xmlHttp.status>=200&&xmlHttp.status<=300||xmlHttp.status==304){
// success
// console.log(xmlHttp.responseText);
obj.success(xmlHttp);
}else{
// error
obj.error(xmlHttp);
}
}
};
// 判断超时
if(obj.timeOut){
timer=setInterval(function(){
console.log("超时");
xmlHttp.abort();
clearInterval(timer);
},obj.timeOut);
}
}
通过ajax进行调用
ajax({
method:"get",
data:{
"name":"ll",
"isbn":1
},
url:"./01php.php",
success:function(xhr){
alert(xhr.responseText);
// alert("success");
},
error:function(res){
alert("error response");
},
timeOut:3000});
这与jquery中的调用一样