我在使用AJAX和CakePHP时遇到了一些JSON2.4的问题。
我希望使用视图呈现数据,但将生成的html保存为变量中的字符串。之后,我想设置一个数组,其中包含此html字符串和其他要作为JSON对象返回的数据。不幸的是,我还没有找到正确的方法。
到目前为止,我的控制器代码使用了CakePHP json的魔力:
//Controller (just parts)
$data = $this->paginate();
if($this->request->is('ajax')) {
$jsonResponse = array(
'jobs' => $data,
'foci' => $foci,
'jobTypes' => $jobTypes,
'count_number'=> $count_number
);
$this->set('jsonResponse', $jsonResponse);
$this->set('_serialize', 'jsonResponse');
} else {
// render regular view
$this->set(compact('data', 'foci', 'jobTypes', 'count_number'));
}
这在javascript控制台中输出了完美的json,除此之外,$data中的数据是纯数据。
有没有可能将$data传递给视图,呈现它,将输出保存到字符串变量$html,并将$html传递给jsonResponse中的作业,而不是$data?
发布于 2014-05-05 10:47:58
是!您可以将视图呈现为变量。你只需要创建一个视图对象。在你的控制器中,试试这个:
$view = new View($this,false);
$view->viewPath='Elements'; // Directory inside view directory to search for .ctp files
$view->layout=false; // if you want to disable layout
$view->set ('variable_name','variable_value'); // set your variables for view here
$html=$view->render('view_name');
// then use this $html for json response
发布于 2015-07-23 11:02:14
对于使用CakePhp3的用户
$view = new View($this->request,$this->response,null);
$view->viewPath='MyPath'; // Directory inside view directory to search for .ctp files
$view->layout='ajax'; // layout to use or false to disable
$html=$view->render('view_name');
不要忘记将其添加到您的名称空间中
use Cake\View\View;
发布于 2015-01-07 09:06:06
Controller::render()
函数实际上通过调用CakeResponse::body()
然后返回当前的CakeResponse
对象来设置响应的主体。这意味着您可以在控制器操作中调用render()
方法,捕获其返回值,然后再次调用CakeResponse::body()
,从而将响应体替换为所需的输出。
示例代码:
$data = $this->paginate();
// Pass the data that needs to be used in the view
$this->set(compact('data', 'foci', 'jobTypes', 'count_number'));
if($this->request->is('ajax')) {
// Disable the layout and change the view
// so that only the desired html is rendered
$this->layout = false;
$this->view = 'VIEW_PASSED_AS_JSON_STRING';
// Call the render() method returns the current CakeResponse object
$response = $this->render();
// Add any other data that needs to be returned in the response
// along with the generated html
$jsonResponse = array(
'html' => $response->body(),
'other_data' => array('foo' => 'bar'),
'bar' => 'foo'
);
// Replace the response body with the json encoded data
$response->body(json_encode($jsonResponse));
}
https://stackoverflow.com/questions/23467734
复制相似问题