php json 返回html标签,php – CodeIgniter在JSON响应中返回HTML

我正在尝试在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个小时才能完成.但我希望你们明白我的要求.

先感谢您.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值