简体   繁体   English

Laravel使用Ajax从购物车中删除

[英]Laravel delete from Shopping Cart using Ajax

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 我想使用Ajax从购物车中删除,我可以毫无问题地添加,但是当我有很多项目时如何在不刷新页面的情况下进行删除,可能需要一个一个地删除,我将html从控制器中的delete函数传递给视图刀片,因此当Im在页面上首次删除时,但在删除一项后无法删除更多

 <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>

delete in controller 在控制器中删除

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM