【问题标题】:CodeIgniter Return HTML in JSON ResponseCodeIgniter 在 JSON 响应中返回 HTML
【发布时间】: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


    【解决方案1】:

    你已经接近正确了。只需要进行一些调整。

    //set the 3rd param to true to make it return data 
    $theHTMLResponse    = $this->load->view('path/to/view.php', null, true);
    
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode(array('ShoppingCartHtml'=> $theHTMLResponse)));
    

    【讨论】:

    • 天啊!非常感谢你的帮助!我真的不知道它只需要一个简单的调整!非常感谢!我被这个问题困扰了3天!在阅读了您的答案后,我想起了 codeigniter 加载视图中的第三个参数。 :)
    • 当然“将第三个参数设置为 true 以使其返回数据”:)
    【解决方案2】:

    我想shoppingcart 被设置为从 $('#...') 返回的东西。那么你只需要这个:

    function (response) { 
        shoppingcart.html(response.ShoppingCartHtml); 
        shoppingcart.close();
    }
    

    【讨论】:

      【解决方案3】:

      首先将视图调用中的第三个参数传递为true

      还有第三个可选参数可以让你改变 函数,以便它将数据作为字符串返回而不是发送 它到您的浏览器。如果您想处理数据,这可能很有用 某种程度上来说。如果将参数设置为 true(布尔值),它将返回 数据。默认行为是 false,将其发送到您的浏览器。 如果要返回数据,请记住将其分配给变量

      $theHTMLResponse= echo $this->load->view('pages/minicart.php', $data,true); //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( 'sucesss'=>1, 'ShoppingCartHtml'=> $theHTMLResponse)
      ));
      

      也使用$.getJSON 并将$(response.ShoppingCartHtml).html(); 替换为response.ShoppingCartHtml

      $.getJSON('/mywebsite/cart/add', {
              itemId: $('.addtocart').data('itemId'),
              quantity: AddedQty
          }, function (response) { 
           if(response.success){
              var html = response.ShoppingCartHtml; 
              shoppingcart.update(html);
              shoppingcart.close();
            }
      });
      

      views

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-23
        • 2018-12-24
        • 2013-09-20
        • 1970-01-01
        • 2021-10-19
        • 2017-10-09
        • 1970-01-01
        相关资源
        最近更新 更多