gpt4 book ai didi

javascript - jquery 中多次出现alert() 框

转载 作者:行者123 更新时间:2023-12-03 09:30:18 25 4
gpt4 key购买 nike

我点击一个简单的“添加到购物车”按钮将商品添加到购物车,如果该商品已存在,则会出现错误 item has 。一切顺利,但是当我第二次单击该按钮时,我必须关闭警报框两次,第三次单击时,我必须关闭警报框三次并且依此类推...这一直持续到我刷新页面为止,同样的事情从头开始

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();
});});

不需要其他事件处理程序。

关于javascript - jquery 中多次出现alert() 框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31530532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com