2012-11-15 29 views
3

我想在提交表单后调用函数,我们可以在jQuery中使用.submit(handler function())执行此操作,但方法描述说,处理程序方法将仅执行表单提交之前。我怎样才能真正实现这一目标?表单提交后我是否应该使用setTimeout或者有没有其他解决方案?在使用JavaScript/jQuery提交表单后调用函数

+4

你不能做一些表单提交后,因为这会导致新的页面被打开,除非你使用AJAX来提交表单。 – Barmar

+1

将您的功能写入目标页面。 – Cedrun

+1

在'submit()'中绑定事件,自己提交表单(使用ajax),然后在表单提交后运行你想要执行的内容 – HungryCoder

回答

0

你可以使用插件http://www.malsup.com/jquery/form/#ajaxSubmit和你需要什么都在回调方法成功

$(document).ready(function() { 
var options = { 
    target:  '#output2', // target element(s) to be updated with server response 

    success:  function() { 
        // callback code here 
        } 

}; 

// bind to the form's submit event 
$('#myForm2').submit(function() { 
    $(this).ajaxSubmit(options); 

    return false; 
}); 
}); 
2
$("#myFormId").on('submit', function(e) { 
    e.preventDefault(); 
    $.ajax({ 
     type: $(this).prop('method'), 
     url : $(this).prop('action'), 
     data: $(this).serialize() 
    }).done(function() { 
     doYourStuff(); 
    }); 
}); 
+1

这不会调用函数“之后”表单提交 – Mihai

+0

更不用说提交可能会失败,而且您只想只有在提交成功时才执行MyfunctionCall() – Mihai

+1

没有足够好地阅读这个问题,但是在表单提交之后做一些事情只能通过ajax来完成,而提交失败的表单并不是问题的一部分。 – adeneo

0

流量:

  1. window.sessionStorage [ '提交']的初始一个空的字符串。
  2. 当您在文本框中输入内容后,点击提交按钮,文本框中的值被保存到window.sessionStorage ['submit']中。 这意味着window.sessionStorage ['submit']不再是空的。它包含一个值。
  3. 提交表单后页面刷新。
  4. onload函数将检查window.sessionStorage ['submit']中是否有任何内容。如果它不是空的,则表示该表单是由用户提交的。 然后它重新设置window.sessionStorage ['submit']为空字符串。

它使用所有主流浏览器支持的会话存储。

<html> 
<body onload="checkSubmitStatus()"> 
<form name="text" action=""> 
<input type="text" id="txtId"> 
<input type="submit" value="submit" onclick="storeInSession()"/> 
</form> 

<script type="text/javascript"> 
function storeInSession(){ 
    window.sessionStorage['submit'] = document.getElementById('txtId').value; 
} 

function checkSubmitStatus(){ 
    if(window.sessionStorage['submit']){ 
     alert('The form was submitted by '+ window.sessionStorage['submit']); 
     window.sessionStorage['submit'] = ''; 
    } 
} 
</script> 
</body> 

+0

对不起,我不明白如果表单已提交,这是怎么知道的。 – SpreeTheGr8

+0

更新了答案 –

+0

谢谢你的解释让我试试看。如果我无法实现,我必须考虑Barmer关于通过Ajax提交表单的建议。 – SpreeTheGr8

相关问题