栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我如何获取更新的购物车会话数组并将其显示在另一个php文件AJAX中

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我如何获取更新的购物车会话数组并将其显示在另一个php文件AJAX中

我认为这会对您有所帮助。我曾经用过自己的代码。有很多改进之处,但我想这是您的学习项目

<?php// Test if the script gets loaded by a POST requestif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {  session_start();  $id = (int)$_POST['id'];  // remove the item from the array  unset($_SESSION['cart'][$id]);}if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {  // get the product ids  // Wy do this? your session is already an array with the ids  $ids = array();  // And here you add the key of the array to ids and not the product_id so you will get the wrong products  foreach ($_SESSION['cart'] as $id => $value) {    array_push($ids, $id);  }  $stmt = $product->readByIds($_SESSION['cart']); // Instead of $ids you can add the session  // this works, but add your fetch in your readByIds method to keep your pre cleaner and return the array with products  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {    ?>    <div >      <p><?= $row['product_name'];?></p>      <p><?= $row['product_price'];?></p>      <button type="button"  data-id="<? $row['product_id']; ?>">Remove</button>    </div>    <?php  }} else {  // Cart session doesnt exist or is empty  // Let the user know the his cart is empty}?><script>  $(function () {    // Remove product from cart    $(".delete-product-cart").click(function (e) {      var        button = $(this),        product_id = button.data('id');      $.ajax({        url: "remove_from_cart.php",        type: "POST",        data: {          id: product_id,        },        beforeSend: function() {          // Disable the button, to prevent duplicate request          button.attr('disabled', 'disabled');        },        success: function (data) { // Response data is not used now          button.parent().fadeOut(300, function () { button.remove();          });        },        complete: function() {          // Make the button enabled again, for when the delete function didnt work the button can be pressed again          button.removeAttr('disabled');        }        error: function () {          //Do Something to handle error        }      });    });  });</script>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/401728.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号