我正在使用代码将数据和 View 从 CodeIgniter Controller 发送到 Ajax
$this->load->model('query_mainmodel');
$data['result'] = $this->query_mainmodel->getcategories();
print $this->load->view('add_content',$data,true);
在 Ajax 中我有
$.ajax({
url: url,
type: 'POST',
dataType: "text",
success: function (response) {
tabID.html(response); //now this time response contains html only
}
});
我得到了 HTML 响应,如何从 ajax 获取数据?
最佳答案
你说你可以获取html,但现在你想要数据。因此,在您的 Controller 中,您可以将 View 和数据作为 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 );
}
});
关于php - 如何从 Codeigniter Controller 中分离 Ajax 响应中的 View 和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808202/