我正在使用 codeigniter 中的 ajax 将商品添加到购物车中。 我的问题是,当我刷新页面时,购物车已更新。我有 ajaxify 它以防止页面刷新。但它没有发生。我的代码是正确的,没有错误。但它仍然不起作用。 我的 Controller 代码是
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
}
我的查看代码是
function insert()
{
var item_id=$("#item_id").val();
var item_name=$("#item_name").val();
var item_price=$("#item_price").val();
var dataString = "&item_id=" + item_id + "&item_name=" + item_name + "&item_price=" + item_price;
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function()
{
alert('hello');
}
});
}
<form id="form">
<input type="hidden" id="item_id" name="item_id" value={{data.id}}> <input type="hidden" id="item_name" name="item_name" value={{data.item_name}}> <input type="hidden" id="item_price" name="item_price" value={{data.price}}>
<p><a href="#" onclick="insert()" class="btn btn-primary">Add to Cart</a></p>
</form>
最佳答案
购物车的概念是在 session 中添加购物车数组 所以在你重新加载页面之前 php 不会感觉到变化
所以你必须用 javascrip 附加表格
// in controller
public function add_to_cart()
{
$item_id = $this->input->post('item_id');
$item_name = $this->input->post('item_name');
$item_price = $this->input->post('item_price');
$data = array(
'id' => rand(5,1000),
'qty' => 1,
'price' => $item_price,
'name' => $item_name,
);
$this->cart->insert($data);
echo json_encode($data) ;
}
// in your javascript
$.ajax({
type: "POST",
url: "http://localhost/wah/cart_test/add_to_cart",
data: dataString,
success: function(data)
{
// just replace YOUR-TABLE-ID with table id
//and complete the tr you want to append
var tr = "<tr><td>"+data.id+"</td><td>"+data.name+"</td></tr>";
$("#YOUR-TABLE-ID tr:last").after(tr);
}
});
关于javascript - 当使用ajax在codeigniter中刷新页面时插入购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28428961/