【发布时间】:2013-09-12 21:53:51
【问题描述】:
我正在尝试在 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('<div class="loading"></div>');
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:
<li>
<h3><?php echo $ProductName; ?></h3>
</li>
到目前为止,我已经尝试回显视图,并使用 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":"\u003cli\u003e\r\n\u003ch3\u003eThe Product Name\u003c/h3\u003e\u003c/li\u003e"}
如果我在 Firebug 控制台中进行检查,在 JSON 选项卡上,它应该显示 ShoppingCartHtml 的 html 代码,用引号括起来,作为 ShoppingCartHtml JSON 响应。
问题是:如何将 ShoppingCartHtml 的 html 代码编码为 JSON 响应?
PS:如果我的问题令人困惑,我深表歉意。英语不是我的一杯茶。即使是输入这个问题,我也需要将近 1 个小时才能完成。但我希望你们能理解我的要求。
提前谢谢你。
【问题讨论】:
标签: php jquery ajax json codeigniter