Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PhalconPHP-在initialize()中重定向_Php_Phalcon - Fatal编程技术网

PhalconPHP-在initialize()中重定向

PhalconPHP-在initialize()中重定向,php,phalcon,Php,Phalcon,在我的项目中,我创建了AjaxController,它可以操作ajax请求。 我想让输入ajax使用的url的用户得到404错误。 在AjaxController.php中,我有: public function initialize() { if (!$this->request->isAjax()) { return $this->response->redirect('error/show404'); } } (当然我有带show4

在我的项目中,我创建了AjaxController,它可以操作ajax请求。 我想让输入ajax使用的url的用户得到404错误。 在AjaxController.php中,我有:

public function initialize() {
    if (!$this->request->isAjax()) {
        return $this->response->redirect('error/show404');
    }
}
(当然我有带show404Action的ErrorController)


它不起作用。当我在浏览器中进入example.com/ajax时,我从AjaxController中的IndexAction获取内容。如何修复它?

我建议通过Dispatcher将用户转发到404页面。这样,URL将保持不变,您将根据SEO规则执行所有操作

public function initialize() {
    if (!$this->request->isAjax()) {
        $this->dispatcher->forward(['controller' => 'error', 'action' => 'show404']);
    }
}
另外,在初始化中进行重定向也不是一个好主意。更多信息请点击此处:

添加我的404方法以防有人需要它。它演示了正确的头处理(同样用于SEO目的)


请尝试在执行器路径()之前的
中执行相同操作。Phalcon的
initialize()
正如它的名字所说,是用来初始化东西的。您可以使用dispatcher在那里进行调度,但不应重定向

您可以查看部分文档。列“是否可以停止操作?”表示是否可以将响应对象返回到完成请求,或
false
停止对其他方法求值并编译视图

需要知道的一件宝贵的事情是,
beforeExecuteRoute()
每次调用操作之前都会执行,因此如果您在操作之间转发,可能会触发几次

public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
    if (!$this->request->isAjax()) {
        return $this->response->redirect('error/show404');
    }
}

我得到警告-前进是无效函数。我的坏。更新了我上面的答案。复制了您的代码,但忘记删除退货。抱歉:)好的,警告消失了,但我仍然从IndexAction获取内容。没有转发到404页:(您能阅读这里的初始化控制器部分吗:并确保您满足使用initialize()的要求吗?如果我在forward()之前转储了一些内容,我会看到它。也许您可以为此使用中间件?
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
    if (!$this->request->isAjax()) {
        return $this->response->redirect('error/show404');
    }
}