我正在尝试在codeigniter中构建一个支持ajax的购物车,现在我遇到了如何将响应作为
HTML进行编码并将其编码为
JSON响应的问题,然后在购物车页面附加响应.
这是javascript代码:
$('.addtocart').on('click', function (event) {
event.preventDefault();
var AddedQty = parseInt($('#attr-quantity').val());
$('#shoppingcart div.cart, #shoppingcart div.loading').remove();
$('#shoppingcart').append('
shoppingcart.open();
$.post('/mywebsite/cart/add', {
itemId: $('.addtocart').data('itemId'),
quantity: AddedQty
}, function (response) {
var html = $(response.ShoppingCartHtml).html();
shoppingcart.update(html);
shoppingcart.close();
});
});
这是购物车控制器的代码:
public function add() {
$this->load->model('cart_model');
$id = $this->input->post('itemId');
$qty = $this->input->post('quantity');
$cart = $this->cart->contents();
$exists = false;
$rowid = '';
foreach ($cart as $item) {
if ($item['id'] == $id) {
$exists = true;
$rowid = $item['rowid'];
$qty = $item['qty'] + $qty;
}
}
if ($exists) {
$this->cart_model->update_item($rowid, $qty);
} else {
$this->cart_model->add_cart_item();
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode(array('ShoppingCartHtml'=> $theHTMLResponse)));
}
下面的代码是我想将其编码为JSON响应的示例代码(不是真正的代码),如ShoppingCartHtml:
<?php echo $ProductName; ?>
到目前为止,我已经尝试回显视图,并使用json_encode对其进行编码,但是我收到了错误.
这是我带来的:
$theHTMLResponse= echo $this->load->view('pages/minicart.php', $data); //THIS LINE THROWS ERROR (I know that I cannot assign what echo-ed into a variable).
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode(array('ShoppingCartHtml'=> $theHTMLResponse)));
我们想要的正确响应示例如下面的代码(如Firebug中所示):
{"MinicartHtml":"
\r\n
The Product Name"}
如果我在Firebug控制台中检查过,在JSON选项卡上,它应该显示ShoppingCartHtml的html代码,用引号括起来,作为ShoppingCartHtml JSON Response.
问题是:如何将ShoppingCartHtml的html代码编码为JSON响应?
PS:如果我的问题令人困惑,我表示歉意.英语不是我的一杯茶.即使输入这个问题,我也需要将近1个小时才能完成.但我希望你们明白我的要求.
先感谢您.