2012-04-24 180 views
1

我有一個表單需要在提交之前進行驗證,POST到一個彈出窗口,然後表單需要重新設置。將ajax提交到彈出窗口

我知道target="newWindowName"onsubmit="window.open('','newWindowName','')"表單屬性的工作,但這並不能讓我在提交後做任何事情。

我知道我可以使用$('form').ajaxSubmit()指定一個提交後功能,但它似乎沒有讓我打開一個新窗口。

我怎樣才能一次完成所有這些事情?

這是我的形式:

<form id="myForm" target="newWindow" autocomplete="on" action="/myUrl" method="post"> 

這是我的javascript:

$('#myForm').submit(function(e) { 
    e.preventDefault(); 
    if ($('#myForm').valid()) { 
     var options = { 
      target: '', 
      beforeSubmit: function() { 
       this.target = "newWindow"; 
       window.open("", "newWindow", "width=500,height=450"); 
      }, 
      success: function() { 
       hideForm(); 
       $('#myForm').resetForm(); 
      } 
     }; 

     $(this).ajaxSubmit(options); 
    } 
    return false; 
} 

回答

2

這裏是我結束了與該會是更優雅的解決方案。

<form id="myForm" target="newWindow" autocomplete="on" action="/myUrl" method="post"> 

然後是JS:

$('#myForm').submit(function(e) { 
    if ($(this).valid()) { 
     var f = this; 
     window.open("",$(this).attr("target"),"width=500,height=500"); 
     setTimeout(function() { // delay resetting the form until after submit 
      hideForm(); 
      f.reset(); 
     }, 0); 
     return true; 
    } 
    else { 
     e.preventDefault(); // only prevent default if the form is not valid 
    } 
    return false; 
}); 

這樣一來,新的窗口將僅會在形式是有效的。

1

你必須使用你的表單標籤target屬性正確的想法。這將自動提交表單到名爲「newWindow」的窗口。 (要始終提交給窗口,使用target="_blank"

麻煩的是要防止形式被提交到新窗口,然後使用JavaScript做一個ajax提交。如果刪除多餘的代碼,你會得到你想要的東西:

$('#myForm').submit(function(e) { 
    if ($(this).valid()) { 
     var f = this; 
     setTimeout(function() { // delay resetting the form until after submit 
      hideForm(); 
      f.reset(); 
     }, 0); 
    } 
    else { 
     e.preventDefault(); // only prevent default if the form is not valid 
    } 
}); 

工作演示:http://jsfiddle.net/2x6wL/

+0

工作,謝謝! – Kay 2012-04-24 01:31:08