提问者:小点点

cakePHP 3.0操作页面控制器::myaction。找不到或无法访问json()。"


我正在将现有的2.5应用程序迁移到3.0。我在使用ajax时遇到404错误。这在CakePHP2.5中运行良好

url:“/cakephp3/pages/myaction.json”

我看不到我可能错过的任何一步。

我敢肯定这是一个路由问题与。json扩展

路线。php

Router::scope('/', function ($routes) {

    Router::extensions(['json', 'xml']);

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'home']);
    $routes->connect('/hotel-training-courses', ['controller' => 'pages', 'action' => 'trainingCourses']);
    $routes->connect('/feature-tour', ['controller' => 'pages', 'action' => 'features']);
    $routes->connect('/contact-us', ['controller' => 'pages', 'action' => 'contact']);
    $routes->fallbacks('InflectedRoute');
});

PagesController.php

public function initialize()
{
    parent::initialize();
    $this->loadComponent('RequestHandler');
}

public function myaction(){

    $this->request->onlyAllow('ajax');

    $userName = $this->request->data['name'];
    $userCompany = $this->request->data['company'];
    $userEmail = $this->request->data['email'];
    $userPhone = $this->request->data['phone'];

    //send an email

}

以前的应用程序能够检测请求类型并返回相同类型的请求。不需要设置渲染。


共1个答案

匿名用户

Router::extensions()必须放置在外部,如果它应该应用于所有路由,则在定义任何作用域和路由之前调用。

如果你想限制扩展解析到一个特定的范围,使用RouteBuilder::e的扩展(),即

Router::extensions(['json', 'xml']);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'home']);
    //...
});

Router::scope('/', function (RouteBuilder $routes) {
    $routes->extensions(['json', 'xml']);

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'home']);
    //...
});

见食谱

请求::只有允许()已重命名为请求::allowmethod(),因此这是您将涉及的下一个问题。

看到没

  • 食谱

此外,您还应该启用调试模式,以便您收到调试此类问题所需的具有适当详细信息的有意义的错误消息。