2012-04-24 88 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