我一直在尝试在 Cakephp 3.0.11 中设置 Ajax 调用。 我在这里遵循了解释:http://book.cakephp.org/3.0/en/views/json-and-xml-views.html
在路由中启用 Json(但我不确定这是否有用):
$routes->extensions(['json', 'xml', 'html']);
我已经在 Controller 中设置了我的示例:
$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 作为布局。这里有什么问题吗?
非常感谢!
最佳答案
如果你想强制每个响应(错误除外)到 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
关于php - Cakephp 3 : Json render View not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078051/