我在使用 AJAX 和 JSON 时遇到了 CakePHP 2.4 的一些问题。
我想用 View 呈现数据,但将生成的 html 保存为变量中的字符串。
之后,我想设置一个数组,其中包含此 html 字符串以及其他数据以作为 JSON 对象返回。不幸的是,我还没有找到正确的方法。
到目前为止,我的 Controller 代码使用了 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'));
}
除了 $data 中的数据是纯数据这一事实之外,这会在 javascript 控制台中输出完美的 json。
是否有可能将 $data 传递给 View ,渲染它,将输出保存到字符串变量 $html,并将 $html 传递给 jsonResponse 中的作业而不是 $data?
最佳答案
是的!您可以将 View 渲染为变量。你只需要创建一个 View 对象。
在你的 Controller 里面试试这个:
$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
关于ajax - 将 View 渲染为字符串,然后在 cakephp 中输出 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23467734/