通用封装ajax代码
封装代码
function Ajax(obj){
var ajax = null;
if(window.XMLHttpRequest){
ajax = new XMLHttpRequest();
}else if(window.ActiveXobject){
ajax = new ActiveXobject("Microsoft.XMLHTTP");
}else{
alert("请升级浏览器");
return false;
}
obj.method = obj.method || "get"; // 默认发送get请求
if(!obj.url){
throw new Error("请求地址不能为空");
}
if(Object.prototype.toString.call(obj.method) != "[object String]"){
throw new Error("请求地址必须是字符串");
}else if(obj.method != "get" && obj.method != "post"){
throw new Error("请求地址必须是get或者是post");
}
if(Object.prototype.toString.call(obj.url) != "[object String]"){
throw new Error("请求地址必须是字符串");
}
if(obj.async == "undefined"){
obj.async = true;
}
if(Object.prototype.toString.call(obj.async) != "[object Boolean]"){
throw new Error("是否异步的参数必须是布尔值");
}
if(obj.data != "undefined"){
if(Object.prototype.toString.call(obj.data) == "[object String]"){
if(obj.data.indexOf("&")>=0){
if(obj.method == "get"){
obj.url += "?"+obj.data;
}else if(obj.method == "post"){
var str = obj.data;
}
}else{
throw new Error("携带的参数格式不对,字符串必须是带'='符号的键值对");
}
}else if(Object.prototype.toString.call(obj.data) == "[object Object]"){
var str = '';
for(var attr in obj.data){
str += attr + "=" + obj.data[attr];
}
}else{
throw new Error("携带的参数格式不对,需要字符串或者对象");
}
}
if(obj.success == "undefined"){
obj.success = function(res){}
}
if(obj.error == "undefined"){
obj.error = function(){}
}
if(Object.prototype.toString.call(obj.success) != "[object Function]" || Object.prototype.toString.call(obj.error) != "[object Function]"){
throw new Error("回调函数必须是函数");
}
ajax.open(obj.method,obj.url,obj.async)
ajax.onreadystatechange=function(){
if(ajax.readyState == 4){
if(ajax.status>=200 && ajax.status<300){
var res;
switch(obj.dataType){
case undefined:
case "json":
res = JSON.parse(ajax.responseText);
break;
case "string":
res = ajax.responseText;
break;
case "xml":
res = ajax.responseXML;
break;
default:
throw new Error("期望的数据格式参数传入错误!");
}
obj.success(res);
}else{
obj.error();
}
}
}
if(obj.method=='post'){
ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
if(obj.data != undefined){
ajax.send(str);
return;
}
}
ajax.send();
}
调用
var pname = document.querySelector("[name='province']").value.trim();
var response = Ajax({
data:{province:pname},
url:"postAjax.php",
method:"post",
asyn:true,
success:function(res){
var arr = JSON.parse(res);
var ul = document.querySelector("ul");
ul.innerHTML = '';
for(var i=0;i<arr.length;i++){
var li = document.createElement("li");
li.innerText = arr[i];
ul.appendChild(li);
}
}
});
get和post的区别:
- get请求的数据展示在地址栏,post在http请求的请求主体中
- get请求的数据长度有限制,post没有限制,除非在服务器设置限制
- get请求的数据格式有限制,必须是url编码的,post的数据没有限制
- get请求不如post安全
- get请求容易有缓存,post没有缓存