alert()框在jquery中出现多次

时间:2015-07-21 04:42:19

标签: javascript jquery

我点击一个简单的添加到购物车按钮将项目添加到购物车,如果该项目已经存在,则会出现错误item already。一切顺利,但当我第二次点击按钮时,我必须关闭警报框两次,第三次点击,我必须关闭警报框三次所以...这一直持续到我刷新页面,同样的事情从头开始

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

错误或成功行为相同

2 个答案:

答案 0 :(得分:1)

你只需要这个

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

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

答案 1 :(得分:0)

完成提交后,只需使用它。它将关闭点击事件。

  $("#addtocart").off('click');