很多時候Ajax的xmlHttpRequest請求都不是並發的,所以可以直接在JS中調用,或者調用jquery中的方法即可;
但是如果考慮到請求並發的情況,而且時間比較長並且頻率也比較高,就需要考慮串連池問題了;
下面是Ajax串連池代碼:
code: var XMLHttp = {
_objPool: [],
_getInstance: function() {
for (var i = 0; i < this._objPool.length; i++) {
if (this._objPool[i].readyState == 0 || this._objPool[i].readyState == 4) {
return this._objPool[i];
}
}
// IE5中不支援push方法
this._objPool[this._objPool.length] = this._createObj();
return this._objPool[this._objPool.length - 1];
},
_createObj: function() {
if (window.XMLHttpRequest) {
var objXMLHttp = new XMLHttpRequest();
}
else {
var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var n = 0; n < MSXML.length; n++) {
try {
var objXMLHttp = new ActiveXObject(MSXML[n]);
break;
}
catch (e) {
}
}
}
// mozilla某些版本沒有readyState屬性
if (objXMLHttp.readyState == null) {
objXMLHttp.readyState = 0;
objXMLHttp.addEventListener("load", function() {
objXMLHttp.readyState = 4;
if (typeof objXMLHttp.onreadystatechange == "function") {
objXMLHttp.onreadystatechange();
}
}, false);
}
return objXMLHttp;
},
// 發送請求(方法[post,get], 地址, 資料, 回呼函數)
sendReq: function(method, url, data, callback) {
var objXMLHttp = this._getInstance();
with (objXMLHttp) {
try {
// 加隨機數防止緩衝
if (url.indexOf("?") > 0) {
url += "&randnum=" + Math.random();
}
else {
url += "?randnum=" + Math.random();
}
open(method, url, true);
setrequestheader("cache-control", "no-cache"); //不緩衝請求頁面
setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); // 設定請求編碼方式
send(data);
onreadystatechange = function() {
if (objXMLHttp.readyState == 4 && (objXMLHttp.status == 200 || objXMLHttp.status == 304)) {
callback(objXMLHttp);
url = null;
data = null;
callback = null;
method = null;
CollectGarbage();
}
}
}
catch (e) {
alert("指令碼出錯:" + e);
}
}
}
};
調用樣本:
//發送資訊
function sendMessage(username, uid, data1, user_to) {
if (isNaN(uid)) return;
var data = "[data]=" + escape(data1);
var url = "Ajax_method.aspx?method=sendMessage&id=" + uid + "&username=" +escape(username) + "&user_to=" + user_to;
XMLHttp.sendReq("post", url, data, function(request) {
var state = request.responseText;
if (state == "shibai") {
alert("發送資訊失敗...");
}
});
}