在我的网站上,我通过 jquery ajax 调用动态加载带有“添加到购物车”按钮的购物产品。对于购物车本身,我使用 jcart,jquery 插件。
然后当我将一个项目添加到购物车时,jcart 调用一个带有 ajax 和 POST 的 php 文件。一切正常,产品已正确添加到购物车,但每次我将商品添加到购物车时页面都会重新加载。 当我不使用 ajax 调用来加载产品时(例如直接在页面中加载它们),一切正常,所以一定是某处存在冲突。 有什么线索吗?
这是我的产品功能和 html。
...
<script>
function loadProducts(str) {
$.ajax({
type: 'GET',
async: true,
url: 'ajax/load.php',
data: {'max-id' : str},
cache: false,
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
});
}
</script>
<script>
$(document).ready(function() {
var n = '';
loadProducts(n);
});
</script>
<script src="jcart/js/jcart.js"></script>
</body>
</html>
可以在这里找到带有 ajax 调用的 jcart 插件: http://conceptlogic.com/jcart/standalone-demo/jcart/js/jcart.js
以下是 jcart.js 中的函数。
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php',
cache: false,
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
error: function(x, e) {
...
}
});
...
function add(form) {
// Input values for use in Ajax post
var itemQty = form.find('[name=' + config.item.qty + ']'),
itemAdd = form.find('[name=' + config.item.add + ']');
// Add the item and refresh cart display
$.ajax({
data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
success: function(response) {
// Momentarily display tooltip over the add-to-cart button
if (itemQty.val() > 0 && tip.css('display') === 'none') {
tip.fadeIn('100').delay('400').fadeOut('100');
}
container.html(response);
$('#jcart-buttons').remove();
}
});
}
...
// Add an item to the cart
// is called from the submit-buttons within each product picture
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
“loadProducts()”函数将其放入每个项目的#products 容器中:
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="SDK12345" />
<input type="hidden" name="my-item-name" value="Product Name" />
<input type="hidden" name="my-item-price" value="1.00" />
<input type="hidden" name="my-item-qty" value="1" />
<ul>
<li><img src="product-image.jpg"/></li>
<li>1.00 Dollar</li>
</ul>
<input type="submit" name="my-add-button" value="Add to cart" class="button" />
</fieldset>
</form>
最佳答案
我猜您是在添加到购物车按钮上的绑定(bind)点击操作中调用 loadProducts() 函数。如果您使用具有默认点击行为的元素。您可能想通过“return false”来防止这种情况;在绑定(bind)点击功能的最后一行。
像这样:
$('a.addtocart').bind('click', function(){
//logic here (ajax)
return false;
});
在你的 success 函数之后还有一个逗号,它在 IE 中可能会变得困惑:
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
去掉逗号
我认为您的 ajax 调用中有错误,请尝试解决...我看不到将产品添加到购物车的 php 文件的逻辑。但是如果你想发送你的表单数据(数量,itemid),序列化你的表单数据就足够了。无需传递额外的获取变量。
function add(form) {
$.ajax({
data: form.serializeArray(),
url: 'yourfile.php',
success: function(response) {
// logic
}
});
}
关于javascript - jquery ajax调用冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515443/