从 GET 到 AJAX post/get 的购物车系统


Shoppingcart system from GET to AJAX post/get

我用PHP为一个网站做了一个购物车。像这样获取:

每个页面都以以下内容开头:

<?php session_start(); 
    require("dbconnect.php");
    if(!isset($_SESSION['cart'])) {
         $cart = array();
         $_SESSION['cart'] = $cart;
     }  
?>

生成的每个产品在网站上生成时都会进行以下检查:

if(!in_array($id, $_SESSION['cart'])) {
    echo '<a href="'.get_site_url(). '/sem?action=add&id=' .$id. '#wpc-products"><img width="20px" style="margin-left: 175px;  margin-top: -42px; float:left" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/voeg-toe.png" alt="Voeg product toe"/></a>';
    }
else {
    echo '<a href="'.get_site_url(). '/sem?action=delete&id=' .$id. '#wpc-products"><img width="20px" style="margin-left: 175px; margin-top: -42px; float:left"  src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/verwijderen.png" alt="Verwijder product"/> </a>';
    }

它的作用:如果ID为$id的产品在$_SESSION['cart']中,则产品将有一个删除按钮,该按钮在单击时删除产品。当产品不在会话购物车中时,产品将有一个"添加"按钮,如果您单击它,它将添加产品。

这一切都很好,但是,我想将此 PHP GET 方法更改为 AJAX GET 函数,因为页面的重新加载似乎有点业余。

所以我在谷歌上搜索,但我在搜索这样的东西时发现的只是Magento或WooCommerce的直接实现的AJAX代码。我尝试编写自己的 AJAX 函数来执行 URL,但到目前为止我还没有管理。有人可以给我一个如何做到这一点的方向吗?我不是在要求直接的解决方案,而只是要求如何做到这一点的方向。

我应该编写一个 AJAX 函数,将其作为单击按钮添加到每个产品中,例如function cart(id) {检查id是否在 PHP 购物车中,或者我应该以不同的方式处理?我是否仍然像现在一样使用PHP Cart,或者我应该将其更改为JavaScript数组?

PS:我在PHP方面还可以,但在JavaScript中是一个完全的菜鸟,但我真的很想学习其中的一些。

编辑:好的,所以我解决这个问题的第一步是使用jQuery.ajax()。但是我可以同时使用 jQuery $.get() 和 $.post() 方法。我知道它们在PHP中的区别,但我不确定在使用AJAX时使用哪一个。

你可以像你说的那样使用 AJAX。基于您提供的代码

        if(!in_array($id, $_SESSION['cart'])) {
    echo '<a class="add-to-cart-btn" data-id="'.$id.'" data-action="add"><img width="20px" style="margin-left: 175px;  margin-top: -42px; float:left" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/voeg-toe.png" alt="Voeg product toe"/></a>';
    }
else {
    echo '<a class="add-to-cart-btn" data-id="'.$id.'" data-action="delete"><img width="20px" style="margin-left: 175px; margin-top: -42px; float:left"  src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/verwijderen.png" alt="Verwijder product"/> </a>';
    }

然后使用 jQuery 处理每次点击具有类add-to-cart-btn锚链接,获取您想要的 id 和操作(如果它尚未在购物车中添加否则删除),并使用 AJAX 将它们发送到服务器。

$(".add-to-cart-btn").click(function(e) {
    e.preventDefault();
    var id=$(this).data('id');
    var action=$(this).data('action');
    var this_button=$(this);
$.ajax({
            url: "/sem?action="+action+"&id="+id,
                    type: "GET",
                    success: function (data)
                    {
                     //you can check your returned data from php here 
                     //and on success toggle data action (because user may click the button again...
                      this_button.data('action', action == 'add' ? 'delete' : 'add');
                    }
            });
          });

当然,这个例子真的很基本。我还没有测试过它,但这样的东西应该可以做你想要的。您应该查找ajax调用的文档,以便您可以看到您拥有的所有选项,处理错误等。

我认为你的代码可能看起来像这样。

  • 编写一个 PHP 页面,以 JSON 格式返回 $_SESSION 变量(JavaScript 对象表示法)。

示例网址:shopping_cart_items.php

<?php
session_start(); 
require("dbconnect.php");
echo json_encode($_SESSION);

然后使用 jQuery 获取数据:

// Gets (JSON) a Javascript Object from  the server
jQuery.getJSON("shopping_cart_items.php",function(items_in_shopping_cart){
    // Loops through all the <a> elements with class shopping_cart_elements
    // (assuming your <a> elements have a distinctive attribute such as a class "shopping_cart_elements")
    jQuery("a.shopping_cart_elements").each(function(index,dom_object){
            // Gets the current <a> element id attribute
            current_dom_obj_id = jQuery(dom_object).attr('id');
            // Checks if current id belongs to the array current_dom_obj_id
            if(items_in_shopping_cart.indexOf(current_dom_obj_id) != -1)
                // Changes the 'href' attribute to'action=add'
                jQuery(dom_object).attr('href','/sem?action=add&id='+id+ '#wpc-products');
            else
                // Changes the 'href' attribute to'action=delete'
                jQuery(dom_object).attr('href','/sem?action=delete&id='+id+ '#wpc-products');
        });
});