你可以在表单提交后调用 jQuery 函数吗?

huangapple go评论93阅读模式
英文:

How can I call a jQuery function AFTER a form is submitted?

问题

如何在表单提交后调用jQuery函数?

我知道如何在提交时调用函数,但我想在提交后并且使用PHP将详细信息添加到数据库后再调用它。

我正在制作一个用户可以将商品放入购物车的网站。这部分运行良好。然而,在将产品发布并添加到购物车后,我想显示一个弹出框来显示购物车。因此,我需要在提交完成后调用该函数。

英文:

How do I call a jQuery function AFTER a form is submitted?

I know how to call a function ON submit, but I want to call it after the post is submitted and details are put into the database with PHP.

I'm making a website where the user can put items into a cart. This works fine. However, AFTER a product is posted and added into the cart I want to display a popup-box displaying the cart. Hence I need the function to be called AFTER the submit has completed.

答案1

得分: 1

你可以从done()函数中实现这一点,例如,假设你的表单和Ajax请求如下所示:

  1. $("#target").on("submit", function(event) {
  2. event.preventDefault();
  3. var theId = $("input[name='id']", this).val();
  4. var request = $.ajax({
  5. url: "script.php",
  6. method: "POST",
  7. data: { id : theId },
  8. dataType: "json"
  9. });
  10. request.done(function(serverData) {
  11. showCart(serverData);
  12. });
  13. request.fail(function(jqXHR, textStatus) {
  14. alert("Request failed: " + textStatus);
  15. });
  16. });

由于Ajax请求默认是异步的,而且应该是异步的,所以当Ajax请求成功时,showCart()函数将被调用。

有关更多详细信息,请查看文档

英文:

> Hence I need the function to be called AFTER the submit has completed.

You can do that from done(), for example, assuming your form and Ajax request are like this:

  1. <form id="target" action="#">
  2. <input type="text" id="id" value="1">
  3. <input type="submit" value="Go">
  4. </form>
  5. $( "#target" ).on( "submit", function( event ) {
  6. event.preventDefault();
  7. var theId = $("input[name='id']",this).val();
  8. var request = $.ajax({
  9. url: "script.php",
  10. method: "POST",
  11. data: { id : theId },
  12. dataType: "json"
  13. });
  14. request.done(function( serverData ) {
  15. showCart(serverData);
  16. });
  17. request.fail(function( jqXHR, textStatus ) {
  18. alert( "Request failed: " + textStatus );
  19. });
  20. });
  21. //....
  22. function showCart(dataForCart) {
  23. //Use dataForCart if needed and show cart
  24. }

Since Ajax requests are asynchronous by default and should be, showCart() will be called when the Ajax request has succeeded.

For more details, check the documentation.

huangapple
  • 本文由 发表于 2023年5月22日 19:41:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定