首先看下面的程式碼片段,我們希望使用者在點擊頁面上的Button時首先將資料提交到指定的第三方頁面,然後再執行背景Page_Load事件。
複製代碼 代碼如下:<body>
<iframe id="WebGatewaySubmissionProcessor_IFrame" name="WebGatewaySubmissionProcessor_IFrame" style="display: none;"></iframe>
<form onsubmit="javascript:if (typeof WebGatewayDoubleSubmission != 'undefined') {WebGatewayDoubleSubmission(this);}" id="Form1" runat="server">
<div id="page">
<asp:Button ID="BtnClientSend" runat="server" />
</div>
<script type="text/javascript" id="WebGatewayScript">
WebGatewayDoubleSubmission = function(o) {
var oldAction = o.action;
var oldOnSubmit = o.onsubmit;
var oldTarget = o.target;
var oldMethod = o.method;
var iframeSubmisionTarget = document.getElementById("WebGatewaySubmissionProcessor_IFrame");
var submitPostIframeSubmission = function() {
o.action = oldAction;
o.target = oldTarget;
o.method = oldMethod;
o.onsubmit = oldOnSubmit;
o.submit();
};
/*iframeSubmisionTarget.onload = submitPostIframeSubmission;*/
eventPush(iframeSubmisionTarget, 'load', submitPostIframeSubmission);
o.action = "http://webgateway.hostedmscrm.com/V2/formprocessor.aspx";
o.target = "WebGatewaySubmissionProcessor_IFrame";
o.onsubmit = null;
o.method = "POST";
o.submit();
};
WebGatewaySubmission = function(o) {
o.action = "http://webgateway.hostedmscrm.com/V2/formprocessor.aspx";
o.method = "POST";
};
function eventPush(obj, event, handler) {
if (obj.addEventListener) {
obj.addEventListener(event, handler, false);
} else if (obj.attachEvent) {
obj.attachEvent('on' + event, handler);
}
}
</script>
</form>
</body>
Form中的onsubmit事件在頁面被提交時觸發,此時首先執行WebGatewayDoubleSubmission指令碼方法,在該方法中,將當前Form的action,onsubmit,target,method緩衝到指定的變數中,然後將Form的action和target指向另一個頁面進行提交,此時頁面上的資料被Post到第三方頁面。然後再使用頁面上隱藏的IFrame來調用submitPostIframeSubmission方法,並將原先的Form進行提交。這裡有一個問題,在上面的代碼中有一行被注釋掉了,原因就是直接使用IFrame的onload方法並不能觸發該事件,從而導致submitPostIframeSubmission方法不能執行,頁面的第二次提交不成功!使用eventPush方法可以有效地解決該問題。
同時,在服務端的Page_Load事件中,需要使用IsPostBack來判斷頁面是否被提交了: 複製代碼 代碼如下:protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//TODO:
}
}
相關資料:
http://www.4ucode.com/Study/Topic/1087401
http://wiki.operamasks.org/pages/viewpage.action?pageId=1835020