问题描述
曾经试图弄清楚几个小时,但无法正常工作!
Been trying to figure this out for hours but can't get it to work!
我正在关注使用Ajax和Ajax实现简单的购物车功能CakePHP
I'm following this tutorial to implement a simple shopping cart feature using Ajax and CakePHP
在CartsController中,我们必须设置:$ this-> autoRender = false;因为Ajax调用不需要加载 ADD视图。但是,当我单击添加到购物车按钮时,它将返回一个空白页,其中包含正确的数量编号。如果我返回上一页并刷新它,则可以看到该商品已添加到购物车。
In the CartsController, we have to set: $this->autoRender = false; since the Ajax call doesn't need to load the 'ADD' view. However, when I click the 'Add to Cart' button, it returns a blank page with the correct quantity number. If I go back a page and refresh it, then I can see the item has been added to the cart.
如何禁用此空白页面(数量为)
How do I disable this blank page (with the qty) from loading and have Ajax just update the cart counter?
CakePHP:
public function add() {
$this->autoRender = false;
if ($this->request->is('post')) {
$this->Cart->addProduct($this->request->data['Cart']['product_id']);
}
echo $this->Cart->getCount();
}
仅供参考:
- addProduct只会在会话中循环访问数组,并增加变量(如果找到)或添加到数组(如果未找到)
- getCount只会返回
Ajax:
<script>
$(document).ready(function(){
$('#add-form').submit(function(e){
e.preventDefault();
var tis = $(this);
$.post(tis.attr('action'),tis.serialize(),function(data){
$('#cart-counter').text(data);
});
});
});
</script>
仅供参考,我在default.ctp中引用了jQuery:
FYI, I'm making this reference to jQuery in my default.ctp:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
推荐答案
请确保在自定义JavaScript代码之前添加了jQuery 。否则,将不会加载 $
变量,并且您的ajax调用也将根本不会执行。
Please check that jQuery is added before your custom javascript code. If not, the $
variable won't be loaded and your ajax call won't execute at all.
这篇关于AutoRender = False在CakePHP中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!