jQuery.ajax,我总是要求两次

时间:2017-04-09 15:37:00

标签: javascript jquery ajax

我将点击功能foo绑定到jquery.ajax中的锚标记。我面临的问题是我必须请求两次或单击锚标记两次才能发出请求。另外我在网络栏下的浏览器中注意到,当我点击锚标签时,没有触发ajax请求。但当我点击两次然后我在网络选项卡中看到两个ajax请求。我不知道发生了什么事?

 <script type="text/javascript">

function show(thelink)
{

    var cat = thelink.innerHTML;
    var productContainer = document.getElementById("productContainer");

    $.ajax({

           type:"POST",
           url:"fetchdata1",
           data:"cat="+cat,

         success:function(data){
            productContainer.innerHTML ="";
            var $productContainer = $('#productContainer');
            $.each(data,function(key,value){
              if(value['newVar'] === 1)
              {
              $productContainer.append("<div id='productBox' class='grid_3'>\n\
             <a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
             <a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
             <span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
             <br/><br/><a href='#' class='remove' onclick='foo(this)' pid='"+value['id']+"'>REMOVE</a></div>");

             }  
             else{

             $productContainer.append("<div id='productBox' class='grid_3'>\n\
             <a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
             <a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
             <span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span></div>"); 
             }
        }) ;

     }      

    });

    return false;
}


  function foo(obj){

            var pid = $(obj).attr("pid");
            $(obj).bind("click", function(){    
                    $.ajax({   
                      type:"POST",
                      url:"removeFromWishlist",
                      data:"pid="+pid,

                      success:function(response){
                        console.log("sent ajax request");
                      }
                    });               
            });

    }  

1 个答案:

答案 0 :(得分:0)

您正在将额外的onclick处理程序绑定到.remove

使用动态添加的元素进行回调时,最好使用document绑定$(document).on("click", 'selector', function(){ ... });上下文中的所有必需事件。

所以不要a href='#' class='remove' onclick='foo(this)' pid='"+执行此操作(请参阅下面的代码段)

$(document).on("click", '#productBox .remove', function(){
    // your ajax call
    $.ajax({   
        type:"POST",
        url:"removeFromWishlist",
        data:"pid="+pid,
        success:function(response){
            console.log("sent ajax request");
        }
    });
});

这将分离您的HTML布局及其行为。

必须避免下面的事情(感谢@charlietfl):

  1. 在同一元素上绑定“click”侦听器两次。
  2. 使用与您的html代码内联的javascript。
  3. 使用onclick属性直接绑定javascript函数。
  4. 不引人注目地使用javascript。
  5. 希望它有所帮助。