Javascript 表单提交后如何进行Jquery回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11534690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do a Jquery Callback after form submit?
提问by geeky_monster
I have a simple form with remote=true.
我有一个带有 remote=true 的简单表单。
This form is actually on an HTML Dialog, which gets closed as soon as the Submit button is clicked.
这个表单实际上是在一个 HTML 对话框上,只要点击提交按钮就会关闭。
Now I need to make some changes on the main HTML page after the form gets submitted successfully.
现在我需要在表单成功提交后对主 HTML 页面进行一些更改。
I tried this using jQuery. But this doesn't ensure that the tasks get performed after some form of response of the form submission.
我用jQuery试过这个。但这并不能确保在表单提交的某种形式的响应之后执行任务。
$("#myform").submit(function(event) {
// do the task here ..
});
How do I attach a callback, so that my code gets executed only after the form is successfully submitted? Is there any way to add some .success or .complete callback to the form?
如何附加回调,以便仅在成功提交表单后执行我的代码?有没有办法向表单添加一些 .success 或 .complete 回调?
采纳答案by geeky_monster
I just did this -
我就是这样做的-
$("#myform").bind('ajax:complete', function() {
// tasks to do
});
And things worked perfectly .
一切都很顺利。
See this api documentationfor more specific details.
有关更具体的详细信息,请参阅此 api 文档。
回答by Bradley Bossard
I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.
我无法让排名第一的解决方案可靠地工作,但发现它有效。不确定它是否是必需的,但我在标签上没有 action 或 method 属性,这确保 POST 由 $.ajax 函数处理并为您提供回调选项。
<form id="form">
...
<button type="submit"></button>
</form>
<script>
$(document).ready(function() {
$("#form_selector").submit(function() {
$.ajax({
type: "POST",
url: "form_handler.php",
data: $(this).serialize(),
success: function() {
// callback code here
}
})
})
})
</script>
回答by Sal
You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.
您必须通过对服务器的 AJAX 调用手动执行操作。这也将要求您覆盖表单。
But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:
不过别担心,这是小菜一碟。下面概述了您将如何处理表单:
- override the default submit action (thanks to the passed in event object, that has a
preventDefault
method) - grab all necessary values from the form
- fire off an HTTP request
- handle the response to the request
- 覆盖默认提交操作(感谢传入的事件对象,它有一个
preventDefault
方法) - 从表单中获取所有必要的值
- 触发 HTTP 请求
- 处理对请求的响应
First, you'll have to cancel the form submit action like so:
首先,您必须取消表单提交操作,如下所示:
$("#myform").submit(function(event) {
// Cancels the form's submit action.
event.preventDefault();
});
And then, grab the value of the data. Let's just assume you have one text box.
然后,抓住数据的价值。让我们假设您有一个文本框。
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
});
And then fire off a request. Let's just assume it's a POST request.
然后发出请求。让我们假设它是一个 POST 请求。
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
// I like to use defers :)
deferred = $.post("http://somewhere.com", { val: val });
deferred.success(function () {
// Do your stuff.
});
deferred.error(function () {
// Handle any errors here.
});
});
And this should about do it.
这应该就可以了。
Note 2:For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.
注意 2:为了解析表单的数据,最好使用插件。它会让你的生活变得非常简单,并提供一个很好的语义来模拟实际的表单提交操作。
Note 2:You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.
注意 2:您不必使用延迟。这只是个人喜好。您同样可以执行以下操作,它也应该有效。
$.post("http://somewhere.com", { val: val }, function () {
// Start partying here.
}, function () {
// Handle the bad news here.
});
回答by edepperson
For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions
对于 MVC,这里是一种更简单的方法。您需要使用 Ajax 表单并设置 AjaxOptions
@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{
... html for form
}
here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form
这是提交代码,这是在文档就绪部分,并将按钮的 onclick 事件绑定到提交表单
$("#btnSubmitFileUpload").click(function(e){
e.preventDefault();
$("#frmUploadTrainingMedia").submit();
});
here is the callback referenced in the AjaxOptions
这是 AjaxOptions 中引用的回调
function displayUploadMediaMsg(d){
var rslt = $.parseJSON(d.responseText);
if (rslt.statusCode == 200){
$().toastmessage("showSuccessToast", rslt.status);
}
else{
$().toastmessage("showErrorToast", rslt.status);
}
}
in the controller method for MVC it looks like this
在 MVC 的控制器方法中,它看起来像这样
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// there is only one file ... do something with it
}
return Json(new
{
statusCode = 200,
status = "File uploaded",
file = "",
}, "text/html");
}
else
{
return Json(new
{
statusCode = 400,
status = "Unable to upload file",
file = "",
}, "text/html");
}
}
回答by Sindre
I do not believe there is a callback-function like the one you describe.
我不相信有像您描述的那样的回调函数。
What is normal here is to do the alterations using some server-side language, like PHP.
这里的正常做法是使用某些服务器端语言(如 PHP)进行更改。
In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.
例如,在 PHP 中,您可以从表单中获取一个隐藏字段,并在它存在时进行一些更改。
PHP:
PHP:
$someHiddenVar = $_POST["hidden_field"];
if (!empty($someHiddenVar)) {
// do something
}
One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.
在 Jquery 中实现它的一种方法是使用 Ajax。您可以监听提交,返回 false 以取消其默认行为并使用 jQuery.post() 代替。jQuery.post 有一个成功回调。
$.post("test.php", $("#testform").serialize(), function(data) {
$('.result').html(data);
});
回答by eel ghEEz
The form's "on submit" handlers are called before the form is submitted. I don't know if there is a handler to be called after the form is submited. In the traditional non-Javascript sense the form submission will reload the page.
在提交表单之前调用表单的“提交时”处理程序。不知道有没有提交表单后要调用的处理程序。在传统的非 Javascript 意义上,表单提交将重新加载页面。
回答by Aikanáro
$("#formid").ajaxForm({ success: function(){ //to do after submit } });