var asyn = {
formSubmit: function (args, action, func) {
this.clearContext();
this.callBack = null;
var subArr = [];
var subArrT = [];
if (b$.type.isArray(args)) {
subArr = args;
} else {
var tag = args.tagName.toLowerCase();
if (tag == "form") { for (var i = 0, num = args.childNodes.length; i < num; i++) { subArr.push(args.childNodes[i]); } }
else { subArr = [args]; }
}
//create asyn form and ifroma
var objForm = document.createElement("form");
objForm.action = action;
objForm.target = "bBankAsynFormSubmit_iframe_1b";
objForm.encoding = "multipart/form-data";
objForm.method = "post";
objForm.id = "bBankAsynFormSubmit_form_1b";
objForm.style.display = "none";
var objIframe = b$.parseDom('<iframe id="bBankAsynFormSubmit_iframe_1b" name="bBankAsynFormSubmit_iframe_1b" src="about:blank" style="display:none;" onload="javascript教程:setTimeout('asyn.complete()',100)"></iframe>')[0];
//add submit value in form
for (var i = 0, num = subArr.length; i < num; i++) {
if (!subArr[i].name && subArr[i].nodeType == 1 && subArr[i].tagName.toLowerCase() == "input") subArr[i].name = "bBankAsynFormSubmit_input_1b_" + i;
var input = subArr[i].cloneNode(true);
subArrT.push(input);
subArr[i].parentNode.replaceChild(input, subArr[i]);
objForm.appendChild(subArr[i]);
}
//submit
document.body.appendChild(objIframe);
document.body.appendChild(objForm);
objForm.submit();
//dispose
for (var i = 0, num = subArrT.length; i < num; i++) { subArrT[i].parentNode.replaceChild(subArr[i], subArrT[i]); }
if (func) this.callBack = func;
},
complete: function () {
var responseText = "";
try {
var objIframe = document.getElementById("bBankAsynFormSubmit_iframe_1b");
if (objIframe.contentWindow) { responseText = objIframe.contentWindow.document.body.innerHTML; }
else { responseText = objIframe.contentDocument.document.body.innerHTML; }
} catch (err) { }
this.clearContext();
if (this.callBack) this.callBack(responseText);
},
clearContext: function () {
if (b$('#bBankAsynFormSubmit_form_1b')) b$('#bBankAsynFormSubmit_form_1b').removeSelf();
if (b$('#bBankAsynFormSubmit_iframe_1b')) b$('#bBankAsynFormSubmit_iframe_1b').removeSelf();
},
callBack: null
};
整合方法
b$.asyn.formSubmit(inputArr, 'xxx.asp教程x', function(d){
alert(d);
});
核心是通過iframe來完成非同步。在頁面放入一個隱藏的iframe,表單有個屬性target,設定target為你要來進行非同步提交的iframe,那麼當你在提交表單的時候,其實是在使用iframe來作為提交顯示載體,頁面其它內容是無重新整理的。
其實原理很簡單,既然iframe是作為顯示載體的,那麼我們擴充下,如果提交的頁面是有傳回值的,那麼傳回值會成為iframe的body裡面的內容,在通過iframe來取得body裡面的內容來,是不是和ajax有點像,這就是以前最早用來實現非同步方法了。
ajax是時間觸發制的,既然要類比ajax,那麼我們也要觸發事件,其實也很簡單,只要使用iframe的onload裝載完成事件就可以了。