[英]alert() box is coming up multiple times in jquery
我單擊一個簡單的“添加到購物車”按鈕以將商品添加到購物車,如果該商品已經存在,則它已經給出了錯誤item already
。 一切順利,但是當我第二次單擊按鈕時,我必須關閉警報框兩次 ,第3次單擊,我必須關閉警報框三次 ,依此類推...直到我刷新頁面為止,同樣的事情從頭開始
jQuery代碼:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function()
{
alert("Item has been added to cart");
},
error:
function(xhr)
{
if (xhr.responseText=="already present")
alert("item is already present in cart");
else if(xhr.responseText=="error")
alert("item cannot be added , server error");
}
});
return false;
//e.preventDefault();
});
});
}
servlet代碼:
if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==2)
{
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
pw.write("already present");
}
else if(k==0)
{
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
pw.write("error");
}
}
錯誤或成功,兩者的行為相同
你只需要這個
$(document).ready(function() {
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {
pid: pid,
user: user
},
success: function() {
alert("Item has been added to cart");
},
error: function(xhr) {
if (xhr.responseText == "already present")
alert("item is already present in cart");
else if (xhr.responseText == "error")
alert("item cannot be added , server error");
}
});
return false;
//e.preventDefault();
});});
不需要其他事件處理程序。
完成提交后只需使用它即可。它將關閉click事件。
$("#addtocart").off('click');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.