2012-02-13 162 views
0

我們開始下面的託管在網站cakephp.org CakePHP的博客教程 - http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.htmlCakePHP重定向方法不起作用?

在這一點上我們堅持對重定向提交表單後(即功能編輯/添加)。這是我們的代碼看起來的樣子:

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($this->referer()); 
     } else { 
      $this->Session->setFlash('Unable to update your post.'); 
     } 
    } 
} 

註釋行$this->redirect($this->referer());後的頁面指的自己......與線補充,它會留下一個空的白頁上。

例子:http://www.drukwerkprijsvergelijk.nl/posts/

請幫助這個小小貓,我們不顧一切。

回答

4

您無法在編輯時使用referer()。那是因爲在第一次POST之後,引用者就像你現在所在的頁面一樣。 referer()只能用於重定向,如果此頁面上沒有表單發佈(例如刪除或訪問該頁面後編輯/添加)。 但即使刪除()你一定要小心。來自「視圖」將導致重定向運行到重定向循環...

您可以將表單作爲隱藏字段存儲在引用程序中,並使用它重定向回來。

+0

之前。 I.e. $ this-> redirect(array('action'=>'index'));也不起作用。 – Jordy 2012-02-13 15:41:50

+4

如果根本沒有重定向,你可能很快會迴應(在php部分 - bootstrap/controller/model/..),因此頭文件已經發送,你的重定向無法工作了。確保所有的php文件都沒有關閉?>並且在重定向之前你什麼都不輸出。 – mark 2012-02-13 16:27:23

+1

謝謝馬克,我做了幾個?>結局,我不會失敗先生! – Jordy 2012-02-14 07:51:17

2

出於上述解釋的原因,您不能在編輯和添加時使用referer()。

使用類似

$this->redirect(array('action' => 'view', $id)); 

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

代替。

您也可以嘗試的URL數組中指定控制器:

$this->redirect(array('controller' => 'posts', 'action' => 'index')); 
2

你有PHP代碼以外的任何空白在PostController中或你的AppController?我只是看着你的編輯頁面的源代碼,它似乎包含一個空格字符。這可能會阻止設置標題,從而阻止重定向的工作。

+0

所有obove的答案都是顯而易見的首先檢查,這是完全有幫助後搜索我的頁面5小時syntex錯誤 – Dashrath 2013-02-18 11:27:00

1

使用這一塊它也沒有工作在我的add()方法過濾功能

header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); // // HTTP/1.1 
    header("Pragma: no-cache"); 
+0

非常感謝你。你救了我15天的工作 – 2016-07-12 09:48:45

+0

:) :) @Tonystark – Shaddy 2016-07-12 10:23:34