Cakephp 3:Json渲染View无法正常工作

Gae*_*l.D 4 php ajax json cakephp

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

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

$routes->extensions(['json', 'xml', 'html']);
Run Code Online (Sandbox Code Playgroud)

我在控制器中设置了我的例子:

$returnObject = new ObjectReturn();
$this->set('returnObject', $returnObject);
$this->set('_serialize', ['returnObject']);
Run Code Online (Sandbox Code Playgroud)

但当我打电话给我时,我得到了:

{
    "message": "Template file \Pages\\score.ctp\ is missing.",
    "url": "\/pages\/score",
    "code": 500
}
Run Code Online (Sandbox Code Playgroud)

如果我创建页面,他会使用default.ctp作为布局来渲染我一些html.这有什么不对?

非常感谢 !

Ste*_*ber 8

如果您想强制每个响应(错误除外)为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);
}
Run Code Online (Sandbox Code Playgroud)

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

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


小智 8

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

  1. AppController.php

编辑初始化函数看起来像这样

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

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

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

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

干杯