2016-09-23 74 views
1

我在我的页面中有3个按钮cart.php 在cart.php中,我具有所有的功能。 当我在结帐页面,我想要添加或删除从购物车中的项目我的页面刷新。 因为我的按钮功能在cart.php中。 我把我的购物车功能在我checkout.php如何使ajax运行php代码,无需刷新页面购物车

我不知道如何使用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>'; 

回答

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

如果($ _ GET [任务] == '增量'),那么增加

如果($ _ GET [就业] ==“月”),那么降低

(或删除,不管你想要发生) 任何输出将在responseText的最终

+0

b我想增加和减少循环中的'$ value'。此代码将显示为文本。我可以通过ajax在循环中增加和减少我的'$ value'吗? –

+0

当然你可以,你只需在结果中填入你的价值。更新你的php中的值,并用js使用返回来更新输入字段。用你的PHP:if($ _GET [job] =='inc'){$ _SESSION ['product _'。$ _ GET ['plus']] + = 1} echo $ _SESSION ['product _'。$ _ GET ['plus “]]; - 这就是你获得js的回报 –