如何使setTimeout脚本在html表单中正常工作

How to make a setTimeout script work properly with an html form?

本文关键字:常工作 工作 表单 setTimeout 何使 脚本 html      更新时间:2023-09-26

这是脚本:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
                function addedCart() {
      document.getElementById("msgs-box").innerHTML = "Item added successfully to cart";
      setTimeout(function() {
        $('#msgs-box').html('');
      }, 6000);
    }
               </script>

形式:

<form action="addToCart" method="post">
<input name="productId" value="${product.id}" type="hidden">
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="submit">
</form>

问题:

当我放置type="submit"并单击"addToCart"时,脚本将被激发,并显示消息,但时间不起作用。无论我把3秒(3000)还是30秒(30000)作为时间值,脚本都不会正确播放时间。消息只会出现和消失。

另一方面,当我放置type="button"并单击"addToCart"时,脚本被激发,消息显示,脚本正在播放时间权限,但值不会发送到cart.jsp

我该如何解决这个问题?我需要将值发送到购物车,我需要脚本在适当的时间工作和播放。

编辑--使用Ajax的新代码

    var $msgBox = $('#msgs-box');
function addedCart() {
    event.preventDefault(); // Prevent default Form Submit Action
    $msgBox.html("Item added successfully to cart");
    setTimeout(function() {
        $msgBox.html('');
    }, 6000);
    $.ajax({
       url : 'cart.jsp',
       data: $("#cartForm").serialize(), // (tip: assign and use an ID for your form)
       success: function( addedCart ) {
         alert( "Item added successfully to cart", addedCart);
       }
    });
}

HTML:

<form id="cartForm" action="addToCart" method="post">
              <br>
              <br>
              <input name="productId" value="${product.id}" type="hidden">
              <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="submit">

您的表单,type="submit"输入的原因是被提交、触发请求、以下标头等。
为了防止这种情况,只需访问event并防止其触发默认操作:

var $msgBox = $('#msgs-box');
function addedCart() {
    event.preventDefault(); // Prevent default Form Submit Action
    $msgBox.html("Item added successfully to cart");
    setTimeout(function() {
        $msgBox.html('');
    }, 6000);
    // Send data to server with AJAX here...
}

由于现在表单数据尚未提交,您可以使用AJAX将序列化的data转发到服务器。

例如:

    // Send data to server with AJAX here...
    $.ajax({
       url : 'addToCartHandler.php',
       data: $("form").serialize(), // (tip: assign and use an ID for your form)
       success: function( response ) {
         alert( "This is my php response: "+ response );
       }
    });