//版權歸屬 WUJXPING
//ajax 1.2
//更新2012-2-20
//1、異步數據加載可以進行加載方式get,post的設定
//2、異步同步模式的屬性設定
//3、數據加載自動超時設置
//4、***數據加載事件的添加,通過事件可以進行服務器數據的實時處理
//5、增加回調函數中用戶自定義參數this.e
//6、增加ajax反復提交控制,只需將ajax對象定義為全局變量,每次提交都會進行等待上次提交的執行結果
//7、修改數據反復提交時XmlHttp對象被反復創建的問題
//8、修復重大BUG,多個AJAX事件覆蓋問題
//服務器數據返回事件
ajax.prototype.ServerEven=function(Func){
this.callback=new delegate(Func);//實例化
}
//創建異步處理對象
ajax.prototype.CreateXMLHttp=function(){
if(this.XmlHttp!=null typeof this.XmlHttp == "object")
return this.XmlHttp;
xmlhttpObj = ["Microsoft.XmlHttp","MSXML2.XmlHttp.5.0","MSXML2.XmlHttp.4.0","MSXML2.XmlHttp.3.0","MSXML2.XmlHttp"];
//根據不同的瀏覽器創建XMLHttpRequest
if(window.ActiveXObject){
for(i=0;ixmlhttpObj.length;i++){ //選擇ie兼容版本
try{
this.XmlHttp = new ActiveXObject(xmlhttpObj[i]);
}catch(err){
continue;
}
if(this.XmlHttp)
break;
}
}
else if(window.XMLHttpRequest){
this.XmlHttp=new XMLHttpRequest();
}
return this.XmlHttp;
}
//開始調用
ajax.prototype.Send=function(){
if(this.isbusy)//ajax正忙
return;
this.isbusy=true;
var xmlhtml=this.CreateXMLHttp(); //創建對象
if(xmlhtml==null){
this.isbusy=false
if(this.callback!=null)
this.callback.run("XMLHttpRequest Create Faild!",this.e);
return;
}
var url=this.url;
var _this=this;
// 加隨機數防止緩存
if (url.indexOf("?") > 0)
url += "randnum=" + Math.random();
else
url += "?randnum=" + Math.random();
xmlhtml.open(this.method,url,this.async);
xmlhtml.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8;");
xmlhtml.setRequestHeader("Cache-Control","no-cache");
xmlhtml.setRequestHeader("Connection","Keep-Alive");
//開啟定時進行超時等待
var timer=setTimeout(function(){
//if(xmlhtml.readyState!=4){
xmlhtml.abort(); //取消本次傳輸
_this.isbusy=false;
if(_this.callback!=null)
_this.callback.run("send timeout!",_this.e);
clearTimeout(timer); //關閉定時器
},this.timeout);
if(this.async)//異步數據加載時狀態變化與事件掛鉤
xmlhtml.onreadystatechange=function(){//接收服務器響應
if(xmlhtml.readyState==4){//判斷是否是完成狀態
if(xmlhtml.status==200){ //判斷是否執行成功
_this.isbusy=false;
clearTimeout(timer); //關閉定時器
if(_this.callback!=null)//開始觸發服務器事件
_this.callback.run(xmlhtml,_this.e);
}
}
};
try{
xmlhtml.send(this.option);
}catch(err){
this.isbusy=false
clearTimeout(timer); //關閉定時器
alert(err);
return;
}
if(!this.async){//同步數據加載時數據返回處理
this.isbusy=false;
clearTimeout(timer); //關閉定時器
if(this.callback!=null)
this.callback.run(xmlhtml,this.e);
}
}
//創建ajax對象
function ajax(url){
this.method="post";//設置數據提交方式
this.async=true;//是否進行異步數據加載模式
this.option=""; //請求的參數
this.url=url;//請求的Url連接
this.timeout=1000*60*1;//默認超時時間為1分鐘
this.e=null;//回調事件中用戶自定義參數
this.XmlHttp=null;//接收異步創建的對象防止反復創建
this.isbusy=false//獲取當前ajax的執行狀態
this.callback=null;//聲明回調事件
// 實現委托的類
delegate=function (func){
this.arr = new Array(); // 回調函數數組
this.add = function(func){
this.arr[this.arr.length] = func;
};
this.run = function(sender,e){
for(var i=0;ithis.arr.length;i++){
var func = this.arr[i];
if(typeof func == "function"){
func(sender,e); // 遍歷所有方法以及調用
}
}
}
this.add(func);
}
}