2015-12-17 57 views
0

我试图用ajax发送产品ID,但我得到相同的ID总是无法使用jQuery AJAX

{% for product in products %} 

    <div id="product"> 
    <a href = '#'> 
    {{ product.id }} 


<form id="productfrm"> 
<input type = "hidden" name = "productid" value="{{ product.id }}"> 
</form> 
</a> 
</div> 

{% endfor %} 

这里给我唯一的产品ID是AJAX脚本

<script type="text/javascript"> 
    $(document).ready(function(){ 
     $('#product>a').on('click',function(){ 
      event.preventDefault(); 
      var fData = $("#productfrm").serialize(); 
      console.log(fData) 
      $.ajax({   
       type: "GET", 
       url: "{% url 'storeView' user=store.user %}", 
       data: fData, 
       success: function(data){ 
        alert('success'); 
       }, 

       error: function(response, error) { 
        alert(error); 
       } 
      }); 
     }) 
    }); 
</script> 

我能确实发送唯一的产品ID点击分区 在此先感谢

+0

你有多个表单具有相同的ID? –

+0

我能做些什么来解决这个问题? –

+0

为什么你在这里有表格?您可以传递productId作为查询参数或路径参数。 –

回答

1

你真的好像不需要在这里的形式。如果你想获取基于一些数据上productId点击,只是有一个onclick听众对你的超链接:

{% for product in products %} 
    <a href = '#' onclick="getStoreView(e, {{ product.id }})"> 
    {{ product.id }} 
    </a> 
{% endfor %} 

然后在你的JS,有一个功能:

<script type="text/javascript"> 
    function getStoreView(event, productId) { 
     event.preventDefault(); 
     console.log(fData); 
     // Send productId as query param of url 
     $.ajax({   
      type: "GET", 
      url: "{% url 'storeView' user=store.user %}", 
      data: fData, 
      success: function(data) { 
       alert('success'); 
      }, 

      error: function(response, error) { 
       alert(error); 
      } 
     }); 
    }); 
</script> 
+0

获得意想不到的令牌) –

0

像罗希特评论,你不应该在页面上多次使用相同的ID。每次循环呈现产品时,它都会打印一个ID为“productfrm”的表单。你使用这个作为fData var的选择器,这就是你的脚本出错的地方。 jQuery不知道使用这个选择器,你正在寻找当前产品中的表单。

你可以做的一件事是从窗体中删除ID。然后换

var fData = $("#productfrm").serialize(); 

var fData = $(this).find('form').serialize(); 

这应该做的工作。但是,将表单放入锚标签中并不是一种好的做法。