我的页面 cart.php 中有 3 个按钮 在 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 做案例工作
if ($_GET[job]=='inc') 则增加
if ($_GET[job]=='dec') 则减少
(或删除,无论你想要发生什么) 任何输出都会以responseText结束
关于javascript - 如何让按钮用ajax运行php代码,而不刷新页面 购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39666593/