如何使setTimeout脚本在html表单中正常工作
How to make a setTimeout script work properly with an html form?
这是脚本:
<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 );
}
});
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JS可以在Chrome中工作,但不能在Firefox中工作
- ajaxToolkit PopupControlExtender不工作.过时的
- HTML标记在脚本标记中工作
- javascript扫雷器floodfill算法不能正常工作