ajax – 将视图渲染为字符串,然后在cakephp中输出json

栏目: jQuery · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/23467734/render-view-to-string-then-output-json-in-cakephp
在使用AJAX和JSON时,我正面临Cake PHP

2.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?

是!您可以将视图渲染为变量.您只需创建一个视图对象.

在你的控制器内试试这个:

$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

翻译自:https://stackoverflow.com/questions/23467734/render-view-to-string-then-output-json-in-cakephp


以上所述就是小编给大家介绍的《ajax – 将视图渲染为字符串,然后在cakephp中输出json》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithms

Data Structures and Algorithms

Alfred V. Aho、Jeffrey D. Ullman、John E. Hopcroft / Addison Wesley / 1983-1-11 / USD 74.20

The authors' treatment of data structures in Data Structures and Algorithms is unified by an informal notion of "abstract data types," allowing readers to compare different implementations of the same......一起来看看 《Data Structures and Algorithms》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

html转js在线工具
html转js在线工具

html转js在线工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具