简体   繁体   English

jQuery:提交表单之前使用Ajax

[英]jQuery: Ajax before submitting form

I'm having a little trouble figuring out how to do an action when submiting a form, but before it is sent. 在提交表单时(但在发送表单之前),我很难弄清楚如何执行操作。 The thing is that the action tag redirects the user to a different site, and I need AJAX to send an email when I click the submit button. 事实是,动作标签将用户重定向到其他站点,并且当我单击“提交”按钮时,我需要AJAX发送电子邮件。 The user should be redirected even if AJAX fails. 即使AJAX失败,也应重定向用户。

I read about $.ajax() but I don't understand how to stop the form submition until jQuery gets a response. 我读到有关$ .ajax()的信息,但是在jQuery收到响应之前,我不了解如何停止表单提交。 Is it done automatically? 它是自动完成的吗?

On another thread I saw that it's recommended to use an input type "button" instead of submit. 在另一个线程上,我看到建议使用输入类型“按钮”而不是提交。 I know that this would allow me to manuallydo a $(form).submit(); 我知道这将允许我手动执行$(form).submit(); later, giving me better control, but I still strugle to fully understand the previous part. 之后,可以更好地控制我,但我仍在努力充分理解上一部分。

I know the answer to this is very simple, and I'm probably running in circles over complicating myself! 我知道答案很简单,而且可能使自己复杂化了很多!

Thanks for your help! 谢谢你的帮助!

To prevent form submission until the ajax request completes, you can disable the async option. 为了在ajax请求完成之前阻止表单提交,可以禁用async选项。

$.ajax({
  url: 'my_url.php',
  async:false,
  .....
});

The recommendation you saw elsewhere is exactly what you need to do. 您在其他地方看到的建议正是您需要做的。

You need to cancel the submission immediately. 您需要立即取消提交。 (by return false ing or by calling e.preventDefault() ) Then, when you get a reply from the server, you can re-submit the form in your AJAX callback. (通过return false或调用e.preventDefault() ),然后,当从服务器收到答复时,可以在AJAX回调中重新提交表单。
(just make sure that you don't do the AJAX request again the second time) (只需确保您第二次不再次执行AJAX请求)

You can use the form's onSubmit attribute. 您可以使用表单的onSubmit属性。

<form action="./something.php" method="post" onSubmit="someFunction();">

If the function returns true the default action takes place, otherwise the default action is prevented. 如果函数返回true则将执行默认操作,否则将阻止默认操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM