【问题标题】:cakephp 2.0 blog tutorial redirect ordercakephp 2.0 博客教程重定向顺序
【发布时间】:2012-04-28 22:15:18
【问题描述】:

所以在博客 cakephp 2.0 教程中,有以下几行 http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html

<?php
public function edit($id = null) {
    $this->Post->id = $id;
    if ($this->request->is('get')) {
        $this->request->data = $this->Post->read();
    } else {
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been updated.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to update your post.');
        }
    }
}

为什么 $this->Session->setFlash('Your post has been updated.');去重定向线之前?一旦它被重定向,为什么会显示消息而不是反之亦然。先重定向再闪消息?

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    除非您将第三个参数设置为false,否则该方法将在重定向后发出exit()

    在这种情况下,setFlash 会将您的消息添加到会话中,然后当您重定向到的页面加载时,该消息可以显示在您的视图中。默认情况下redirect 调用exit,所以你放在它之后的任何东西都不会被执行。即使将第三个参数设置为falsesetFlash 的行为也不会改变。

    当您希望消息只是页面的一小部分时,您可以使用它,例如您在 SO 上收到的“此帖子已被编辑”或“已发布新答案”消息。

    如果您想在重定向之前显示 Flash 消息(即在 HTML 中重定向),您可以在控制器上使用 flash 方法代替(请注意,该消息将有一个完整的页面自己的):

    与redirect() 一样,flash() 方法用于在操作后将用户引导至新页面。 flash() 方法的不同之处在于它在将用户传递到另一个 URL 之前显示一条消息。

    第一个参数应该保存要显示的消息,第二个参数是一个相对于 CakePHP 的 URL。 CakePHP 将在转发用户之前显示 $message 的 $pause 秒。

    如果您希望闪现的消息使用特定模板,您可以在 $layout 参数中指定该布局的名称。

    将首先显示显示您的消息的页面,然后在几秒钟后自动重定向。您可以选择将布局作为第四个参数传入,以更好地控制其外观。

    $this->flash('Your post has been updated.', array('action' => 'index'), 5);
    

    http://book.cakephp.org/2.0/en/controllers.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      相关资源
      最近更新 更多