ajax封装:get、post
使用传入一个对象obj解决ajax参数问题,obj中应包含:
type :数据请求方式
url :请求的资源路径
data : 向服务器传递的请求参数数据 (这里使用urlencoded格式)
fnSuc :服务器响应成功时,前端需要执行的回调函数
function ajax(obj){
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
var str = '';
for(var i in obj.data){
str += i + "=" + obj.data[i] + "&";
}
str = str.replace(/&$/,"");
if(obj.type.toLowerCase() == "get"){
if(str == ""){
xhr.open(obj.type,obj.url,true);
}else{
xhr.open(obj.type,obj.url+"?"+str,true);
}
xhr.send();
}
if(obj.type.toLowerCase() == "post"){
xhr.open(obj.type,obj.url,true);
// 设置请求头 content-type 为 urlencoded
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(str);
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText;
obj.fnSuc(data);
}
}
}
}