function obj2str(data) {
data = data || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
data.t = new Date().getTime();
var res = [];
for (var key in data){
//在URL中是不可以出现中文的,如果出现了中文需要转码,可以调用encodeURIComponent方法,URL中只可以出现字母、数字、下划线
res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
}
return res.join("&");
}
function myAjax(option){
var params = obj2str(option.data);//key=value&key=value;
var xmlhttp,timer;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (option.type.toUpperCase()==="GET") {//toLowerCase将大写转化为小写
xmlhttp.open("GET",option.url+"?"+params,true)
xmlhttp.send();
}else{
xmlhttp.open("POST",option.url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params);
}
xmlhttp.onreadystatechange = function (ev2) {
if (xmlhttp.readyState === 4){
clearInterval(timer);
//判断是否请求成功(Http状态码大于等于200,且小于300,和状态码等于304为请求成功)
if (xmlhttp.status>=200&&xmlhttp.status<300||xmlhttp.status===304) {
option.success(xmlhttp);
}else{
option.error(xmlhttp);
}
}
};
if (option.timeout){
timer = setInterval(function () {
console.log("中断请求");
xmlhttp.abort();
clearInterval(timer);
},option.timeout);
}
}