这是我整理的ajax的方法,有单独的get方法,post方法,也有ajax的完全封装
function get(url,data,callBack){
var xhr = getXHR();
if(!!data && data instanceof Function){
callBack = data;
data = undefined;
}
url = url + "?rand=" + new Date().getTime();
if(!!data){
url += "&" + serialize(data);
}
xhr.open("get",url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState ===4){
if(xhr.status === 200){
callBack(xhr.responseText);
}else{
callBack("请求错误 错误提示:" + xhr.status + " ; 错误原因:" + xhr.statusText);
}
}
}
}
function post(url,data,callBack){
var xhr = getXHR();
if(!!data && data instanceof Function){
callBack = data;
data = undefined;
}
data = !!data ? serialize(data) : null;
xhr.open("post",url);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange=function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
callBack(xhr.responseText);
}else{
callBack("请求出现错误:错误提示" + xhr.status + ";错误原因:" + xhr.statusText);
}
}
}
}
function ajax(param){
if(!!param.data){
param.data = serialize(param.data);
}
if(param.type.toLowerCase() === "get"){
param.url += "?rand=" + new Date().getTime();
if(!!param.data){
param.url += "&" + param.data;
}
}
var xhr = getXHR();
xhr.open(param.type,param.url);
if(param.type.toLowerCase() === "post"){
xhr.setRequestHeader("Content-Type","application/x-www-form-urlcoded");
xhr.send(param.data);
}else{
xhr.send();
}
xhr.onreadystatechange = function(){
if(xhr.readyState !=4) return ;
if(xhr.status == 200){
param.success(xhr.responseT);
}else{
if(!!param.error){
param.error(new Error("请求出现错误:错误提示" + xhr.status + ";错误原因:" + xhr.statusText));
}
}
}
}
function getXHR(){
var xhr = null;
if(!!window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = ActiveXObject();
}
return xhr;
}
function serialize(obj){
var paramArr = [];
for (var key in obj) {
paramArr.push(key + "=" + encodeURIComponent(obj[key]));
}
return paramArr.join("&");
}
以上代码仅供参考