我想使用AJAX将产品id的值传递给cart.php,并将其显示在index.php中的div.cart中,但我不知道如何。请帮忙。
产品产品描述
添加到购物车$('a').on('click', function(e){
$.ajax({
url:
data:
})
e.preventDefault();
});
当然可以:)!
所以,首先,让我们把事情搞清楚。您正在以<div class="thumbnail">
形式显示产品列表,对吗?所以你的PHP/HTML在现实中应该看起来有点像这样:
<?php
foreach($database_recordset as $row) {
echo '
<div class="thumbnail>
<img src="'.$row['img_src'].'" alt="'.$row['img_alt'].'" />
<div class="caption">
<h4>'.$row['product_name'].'</h4>
<p>'.$row['product_description'].'</p>
<a id="p-'.$row['id'].'" onclick="addCart(this)">Add to Cart</a>
</div> <!-- You were missing a /div here if I guessed right the structure -->
</div>';
}
?>
所以我简单地标记了链接p-#ID
,其中#ID是数据库中产品的ID,并添加了一个以this
为参数的onclick
事件。现在您需要一个包含AJAX请求的函数addCart
。
<script type="text/javacscript">
function addCart(elm) {
// First we need the clean ID of the product
var id = elm.id.split('-')[1]; // We split with '-' as separator and take the second element of the resulting array
$.ajax({
url: "cart.php",
type: "POST", // or GET whatever but POST is usually better
data: { id: id },
success: function(response) {
if (response.status == 'OK') { // You should always test the response of an ajax request
// show a message, update the cart icon or whatever
}
}
});
}
</script>
您需要修改这样的代码。Href需要删除,否则它会在该页面上重定向您。下面给出的是您的代码的示例
<div class="thumbnail>
<img src="" alt="" />
<div class="caption">
<h4>Product</h4>
<p>Product Description</p>
<a id="id=(id from table products)">Add to Cart</a>
</div>
$('a').on('click', function(e){
$.ajax({
url: cart.php
data:{id:$(this).attr("id")}
})
e.preventDefault();
});
您需要停止链接后的浏览器,然后发出ajax请求并将响应插入目标div。
您可以使用jquerys的load
方法在一次调用中实现这一点:
$('a.clickme').click(function(ev){
ev.preventDefault();
$('div.cart').load($(this).attr('href'));
});
注意,我在链接中添加了一个类,否则你的代码将捕获所有链接点击,包括网站导航等
<a href="cart.php?id=(id from table products)" class="clickme">Add to Cart</a>