【问题标题】:How to separate view and data in Ajax response from codeigniter controller如何将 Ajax 响应中的视图和数据与 codeigniter 控制器分开
【发布时间】:2017-08-22 02:53:45
【问题描述】:

我正在使用代码将数据和视图从 CodeIgniter 控制器发送到 Ajax

$this->load->model('query_mainmodel');
$data['result'] = $this->query_mainmodel->getcategories();  
print $this->load->view('add_content',$data,true);

在阿贾克斯我有

$.ajax({
     url: url,
     type: 'POST',
     dataType: "text",
     success: function (response) {
       tabID.html(response); //now this time response contains html only
     }
});

我得到了 HTML 作为响应,如何从 ajax 获取数据?

【问题讨论】:

  • 看起来你正在这样做。数据的价值是什么?
  • 现在 Ajax 响应中的数据值是 html,为了避免混淆,我在 ajax(响应数据)中编辑了代码
  • 您或多或少期待或希望得到什么?
  • 我期待包含视图的数据库查询结果
  • 所以你想要两件事,对吧?

标签: php jquery ajax codeigniter


【解决方案1】:

你说你可以得到 html,但现在你想要数据。因此,在您的控制器中,您可以将视图和数据作为 json 传回:

$data['result'] = $this->query_mainmodel->getcategories();

echo json_encode( array(
    'view_html' => $this->load->view('add_content',$data,true),
    'data'      => $data['result']
));

然后在你的 JS 中:

$.ajax({
     url: url,
     type: 'POST',
     dataType: "json", // <- make sure to change this
     success: function (response) {
       // view HTML available like this
       console.log( response.view_html );

       // data available like this
       console.log( response.data );
     }
});

【讨论】:

  • 顺便说一句,你可以做很多事情。尝试 5 或 10 件事。它非常强大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 2012-03-22
相关资源
最近更新 更多