//type:请求类型get/post url:服务器 地址 data:需要上传到服务器的数据 fnSuc:处理服务器返回的数据的函数
function ajax(type,url,data,fnSuc){
if(window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();//现代浏览器
} else {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");//兼容旧版本
}//兼容性
var str = "";
for(var attr in data){
str += attr+"="+data[attr]+"&";
}
str = str.replace(/&$/,"");//去掉最后一个&符号
if(type.toUpperCase() == "GET"){ //toUpperCase()把所有字符全都转换为大写
xhr.open("get",url+"?"+str,true);//get请求数据放到url地址后边 地址与数据用?隔开
xhr.send();
}
if(type.toUpperCase() == "POST"){
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");// 固定写法 post向后台传数据时要用
xhr.send(str);//post的传递数据放到send里边
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
var data = xhr.responseText;
fnSuc(data);
}
}
}
}