【问题标题】:Cakephp 3 : Json render View not workingCakephp 3:Json 渲染视图不起作用
【发布时间】:2015-11-11 17:21:08
【问题描述】:

我一直在尝试在 Cakephp 3.0.11 中设置 Ajax 调用。 我已经按照这里的解释:http://book.cakephp.org/3.0/en/views/json-and-xml-views.html

在路由中启用了 Json(但我不确定这是否有用):

$routes->extensions(['json', 'xml', 'html']);

我已经在控制器中设置了我的示例:

$returnObject = new ObjectReturn();
$this->set('returnObject', $returnObject);
$this->set('_serialize', ['returnObject']);

但是当我进行 ajax 调用时,我得到了:

{
    "message": "Template file \Pages\\score.ctp\ is missing.",
    "url": "\/pages\/score",
    "code": 500
}

如果我创建页面,他会为我呈现一些 html,并使用 default.ctp 作为布局。这里有什么问题?

非常感谢!

【问题讨论】:

  • 您是否按照here 的说明在控制器中加载了RequestHandlerComponent
  • 顺便说一句,要启用json 使用扩展和请求处理的视图,您的网址需要使用.json 扩展,例如/pages/score.json
  • 您好,感谢您的回答。我已经升级到 Cake 的最新版本,现在它可以工作了。也许一个错误是正确的。谢谢你的回答!
  • 这在您升级时有效,原因如下:As of 3.1.0 AppController, in the application skeleton automatically adds '_serialize' => true to all XML/JSON requests. You will need to remove this code from the beforeRender callback if you want to use view files. from book.cakephp.org/3.0/en/views/…

标签: php ajax json cakephp


【解决方案1】:

要在你的 cakephp 3 应用程序中实现一个 json/xml 渲染视图,你需要在你的应用程序中编辑两个文件

  1. AppController.php

将初始化函数编辑成如下所示

public function initialize() {
    parent::initialize();
    $this->loadComponent('RequestHandler');/*This line loads the required RequestHandler Component*/
}
  1. routes.php(在您的配置文件夹下)

编辑 Router::scope() 使其看起来像这样

Router::scope('/', function ($routes) {
    $routes->extensions(['json', 'xml', 'ajax']);
    /*Other route definitions as already existing*/
}

您现在可以通过添加 .json 来加载 json 视图,或者通过将 .xml 添加到通常加载您的 html 的链接中来加载 xml。

干杯

【讨论】:

    【解决方案2】:

    如果您想将每个响应(错误除外)强制转换为 JSON(并跳过模板),您可以将此代码放在 AppController.php 中

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }
    
    public function beforeRender(Event $event)
    {
        $this->RequestHandler->renderAs($this, 'json');
        $this->response->type('application/json');
        $this->set('_serialize', true);
    }
    

    这会加载 RequestHandlerComponent,强制渲染为 JSON,强制响应类型为 JSON,并使用模板跳过。

    更多的手册在这里:http://book.cakephp.org/3.0/en/controllers/components/request-handling.html

    【讨论】:

    • 非常感谢!!我疯狂地输出json!好像设置$this->set('_serialize', $vars); 还不够!!提示:也适用于 CakePHP 2!
    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多