【问题标题】:CakePHP: Redirect not workinCakePHP:重定向不起作用
【发布时间】:2013-04-21 10:42:07
【问题描述】:

我的控制器中有以下代码:

class ContactsController extends AppController {
    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');

    public function index() {
        $this->set('contacts', $this->Contact->find('all'));
    }

    public function view($id) {
        if (!$id) {
            throw new NotFoundException(__('Invalid contact'));
        }

        $contact = $this->Contact->findById($id);
        if (!$contact) {
            throw new NotFoundException(__('Invalid contact'));
        }
        $this->set('contact', $contact);
    }

    public function add() {                 
        if ($this->request->is('post')) {
            $this->Contact->create();
            if ($this->Contact->save($this->request->data)) {
                $this->Session->setFlash('Your contact has been saved.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your contact.');
            }
        }
    }
}

在 add() 方法中,我有 $this->redirect(array('action' => 'index')); 行,我希望这行在我的视图中重定向回我的索引页面。但我得到的只是一张空白的白页。

任何帮助表示赞赏。

问候, 斯蒂芬

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    您的代码看起来有效;我在您提供的代码中没有看到错误。

    有几个可能的原因;

    • 您的代码中的其他地方有错误,但是由于禁用了调试,因此 cake php 不输出错误消息。通过在app/Config/core.php - Configure::write('debug', 2); 中将调试设置为 1 或 2 来启用调试
    • 您的应用程序正在向浏览器输出某些内容在发送重定向标头之前。这可能是由任何 <?php?> 之前或之后的(不可见)空白引起的。这将导致“标头已发送”警告,并且浏览器不会重定向。 StackOverflow 上有很多关于这种情况的问题,例如:How to fix "Headers already sent" error in PHP

    注意; 在 CakePHP 中,在任何重定向语句之前放置 return 是一种很好的做法;这将允许对您的应用程序进行更好的单元测试,即:

    return $this->redirect(array('action' => 'index'));
    

    更新;查找原因的附加“指针”

    跟踪这类问题可能比较麻烦,我再补充一点

    • 如果您使用AuthSecurity 组件,其中之一可能会导致“问题”(例如,授权失败或发布的数据被标记为“无效”,这将由“ blackHole()' 回调。在您的 AppController 中禁用两者以检查问题是否仍然存在
    • 如果问题仍然存在, 可能正在发送标头(如前所述),但没有出现警告/错误。要查找 ifwhere 这些标头的发送位置,请将此代码添加到您的“添加”操作中;

    调试代码:

    if (headers_sent($file, $line)) {
        exit("headers were already sent in file: {$file}, line number: {$line}");
    }
    

    【讨论】:

    • 我已打开调试,没有收到任何错误/警告消息,也没有收到任何“PHP 已发送标头”消息。
    • @stephen 这可能需要您进行一些调试,我添加了一些额外的指针/提示来缩小您的问题,也许它们很有用
    • 感谢@thaJeztah,问题已解决,我在 core.php 中有空格,但都没有按预期工作。您的调试代码有效。再次感谢。
    • 非常感谢这段关于 headers_sent() 的代码,它拯救了我的一天!!
    • @user1555112 很高兴我能提供帮助,我知道很难找到这些错误,尤其是在没有显示错误的情况下:)
    【解决方案2】:

    经过大量研究,我终于找到了解决方案。

    请使用

    ob_start(); in AppController.php

    ob_start();
    class AppController extends Controller {
         function beforeFilter() {
             parent::beforeFilter();
         }
    }
    

    【讨论】:

    • 为什么会这样!?我遇到了几个小时的麻烦,但这个简单的技巧解决了这个问题。我需要一些启示!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2017-10-07
    • 2020-01-12
    相关资源
    最近更新 更多