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装载完成事件就可以了。