如何使一个按钮运行php代码与ajax,无需刷新页面购物车

How to make a button run php code with ajax, without refreshing the page Shopping cart

本文关键字:刷新 购物车 ajax 何使一 按钮 运行 代码 php      更新时间:2023-09-26

我有3个按钮在我的页面cart.php在cart.php我有所有的功能工作。当我在结帐页面,我想从购物车中添加或删除一个项目,我的页面刷新。因为我的按钮函数在cart。php中。我在checkout。php

中调用购物车函数

我不知道如何使用ajax,但我认为ajax将帮助我在这方面…我怎么能运行这个代码不去购物车和发送到位置:结帐…?

这是我在cart.php上的按钮。

 if(isset($_GET['plus'])){
   $_SESSION['product_'.$_GET['plus']]+=1;
   if($_SESSION['product_'.$_GET['plus']] < 1){
   header('Location: checkout.php');
   }else{
   header('Location: checkout.php');
    }
}

 if(isset($_GET['remove'])){
   $_SESSION['product_'.$_GET['remove']]--;
   if($_SESSION['product_'.$_GET['remove']] < 1){
   header('Location: checkout.php');
   }else{
   header('Location: checkout.php');
    }
}
 if(isset($_GET['delete'])){
    $_SESSION['product_'.$_GET['delete']] = '0';
    header('Location: checkout.php');
}
$btn_add='<a class="btn btn-success" href="cart.php?plus='.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
$btn_remove = '<a class="btn btn-warning" href="cart.php?remove='.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
$btn_delete='<a class="btn btn-default delete_btn" href="cart.php?delete='.$id.'"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';
    <script>
    function doChanges(job,div,id) {
            try { req = window.XMLHttpRequest?new XMLHttpRequest(): 
                  new ActiveXObject("Microsoft.XMLHTTP"); 
                 } catch (e) {  /* No AJAX Support */ }
            req.open('get','yourphp.php?job='+job+'&id='+id);
            // let the php echo the resultvalue
            req.onreadystatechange = function() {
             handleResponse(div);
            };
            req.send(null);
    }
    function handleResponse(div) {

           if ((req.readyState == 4) && (req.status == 200)) {
               val=req.responseText;
               document.getElementById(div).value=val;
           }
    }
    </script>
<div id="result"></div>
<a href="javascript:doChanges('inc','result','optionalcartitemid'> increase</a>
<a href="javascript:doChanges('dec','result','optionalcartitemid'> decrease</a>

你的php需要为inc/dec做case工作

if ($_GET[job]=='inc') then increase

if ($_GET[job]=='dec') then reduce

(或删除,无论你想发生什么)任何输出将以responseText

结尾