Laravel使用Ajax从购物车中删除 [英] Laravel delete from Shopping Cart using Ajax

查看:96
本文介绍了Laravel使用Ajax从购物车中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Ajax从购物车中删除,我可以毫无问题地添加,但是当我有很多项目时,如何在不刷新页面的情况下进行删除,可能需要一个一个地删除,即时通讯将html从删除功能中传递出去在控制器中查看刀片,因此当Im在页面上第一次删除时,但是在删除一项后无法删除更多

I want to delete from Cart using Ajax, I'm adding with no problem but how can I delete without refresh the page while I have many items and may I need to delete one by one, Im passing the html from delete function in controller to view blade, so when Im at the page for the first time it deletes but after delete of one item cant delete more

 <script>
 $(function(){ 
  $('.remove_item').on("click", function () { 
  var id = $(this).data('id'); 
  $.ajax({
         type: 'DELETE',
         url: "cart/"+ id,  
         data: {'_token': $('input[name=_token]').val()},
         success: function (data) {
           $('#cart_product').html(data);        
         }               
    });
   });
 });
</script>

在控制器中删除

public function destroy($id)
{
     Cart::remove($id);
     $products = Cart::content();
     foreach($products as $Product){

     echo '<div class="OrderItem_root styles_base styles_spacing-base">
           <div class="OrderItem_quantity styles_just-right styles_base 
           styles_spacing-base">'.$Product->qty.'</div>
           <div class="OrderItem_container">
           <div class="OrderItem_category"></div>
           <div class="OrderItem_itemHeader">
           <div id="titletest" class="OrderItem_name styles_just-right styles_base styles_spacing-base">'.$Product->name.'</div>
           <div id="cartprice" class="OrderItem_total">$'.$Product->price*$Product->qty.'</div>
            <input id="mycartprice" type="text" name="mycartprice" value="'.$Product->price.'"  hidden="">
         </div>
        <div>
        </div>
      <div>
     <button class="remove_item OrderItem_action Button_root" data-id="'.$Product->rowId.'" data-price="'.$Product->price*$Product->qty.'" data-qty="'.$Product->qty.'" type="submit">Remove</button>

     </div>
    </div>
   </div>';
   }
 }

推荐答案

这是因为您的元素是动态更新的,因此您应该再次附加事件. 改用以下代码:

This is because your element is dynamically updated and you should attach event again. use this code instead:

     <script>
     $(function(){ 
 $(document).on('click','.remove_item', function () { 
      var id = $(this).data('id'); 
      $.ajax({
             type: 'DELETE',
             url: "cart/"+ id,  
             data: {'_token': $('input[name=_token]').val()},
             success: function (data) {
               $('#cart_product').html(data);        
             }               
        });
       });
     });
    </script>

这篇关于Laravel使用Ajax从购物车中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆