CodeIgniter 是一个基于 PHP 的轻量级 Web 应用框架,它提供了丰富的库和辅助函数来简化开发过程。AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。结合 CodeIgniter 和 AJAX 可以实现动态更新购物车中的商品数量。
CodeIgniter:
AJAX:
class Cart extends CI_Controller {
public function update_quantity() {
$item_id = $this->input->post('item_id');
$new_quantity = $this->input->post('new_quantity');
// 更新数据库中的商品数量
$this->load->model('cart_model');
$this->cart_model->update_quantity($item_id, $new_quantity);
// 返回更新后的购物车信息
$cart_data = $this->cart_model->get_cart();
echo json_encode($cart_data);
}
}
class Cart_model extends CI_Model {
public function update_quantity($item_id, $new_quantity) {
$data = array(
'quantity' => $new_quantity
);
$this->db->where('id', $item_id);
$this->db->update('cart_items', $data);
}
public function get_cart() {
// 获取购物车数据
return $this->db->get('cart_items')->result_array();
}
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('.update-quantity').on('change', function() {
var item_id = $(this).data('item-id');
var new_quantity = $(this).val();
$.ajax({
url: '<?php echo base_url("cart/update_quantity"); ?>',
type: 'POST',
data: { item_id: item_id, new_quantity: new_quantity },
dataType: 'json',
success: function(response) {
// 更新页面上的购物车显示
$('#cart-items').html(response);
},
error: function(xhr, status, error) {
console.error("AJAX Error: " + status + error);
}
});
});
});
</script>
<!-- 示例:更新购物车数量的输入框 -->
<input type="number" class="update-quantity" data-item-id="1" value="2">
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
通过以上步骤和方法,可以实现一个基于 CodeIgniter 和 AJAX 的动态购物车更新功能。
领取专属 10元无门槛券
手把手带您无忧上云