2014-10-03 121 views
0

我在控制器中有一個測試函數,用於生成表單頁面。如何在codeigniter中提交表單後重定向到上一頁

public function testing() 
    { 
       $this->form_validation->set_rules('test', 'TEST', 'required'); 

       if ($this->form_validation->run()) { 
       redirect($this->agent->referrer()); 
       } else { 
       $data['title'] = 'Testing'; 
       $data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message'); 
       $this->load->view('templates/header', $data); 
       $this->load->view('pages/nonmember/testing', $data); 
       $this->load->view('templates/footer'); 
       }   
    } 

測試視圖的代碼如下

<div id="message"><?php echo $message; ?></div> 
<?php echo form_open(base_url()."testing");?> 

    <p> 
    <?php echo form_input('test');?> 
    </p> 

    <p><?php echo form_submit('submit', 'Submit');?></p> 

<?php echo form_close();?> 

如果用戶來自另一個頁面讓說About page測試頁面提交我正確的形式,他們得到重定向回About page後想。但由於引薦代理人停留在testing page,因此提交之後它將停留在那裏,而不是重定向到About page

回答

0

加入這一行需要在控制器的測試功能

$this->session->set_flashdata('url',$this->agent->referrer()); 

改變這在功能測試

if ($this->form_validation->run()) { 
     redirect($this->session->flashdata('url')); 
    } else { 
     $this->session->set_flashdata('url',$this->agent->referrer()); 
     //load the view 
    } 
... 

,或者您也可以提交一個隱藏字段一樣,

form_hidden('rURL', $this->agent->referrer()); 

然後只需在controll中使用它的值呃。

if ($this->form_validation->run()) { 
      redirect($this->input->post('rURL')); 
     } else { 
    ... 
+0

首先,它是'set_flashdata()'。其次,這兩種解決方案都可以工作,但如果用戶在登陸後刷新測試頁面,或者用戶輸入不符合驗證規則,那麼頁面將被刷新,意味着引用者變成了自己,因此測試頁面重定向回自己 – user1906399 2014-10-03 08:26:41

+0

而不是使用代理類, $ _ SERVER。它也可以工作 – gahse 2014-10-03 10:04:18

+0

如果用戶輸入錯誤的數據或在從另一個頁面來回之後刷新測試頁面,則什麼都不會起作用。隨着頁面刷新引用正在從其他頁面的網址更改爲測試頁面的網址。 – user1906399 2014-10-03 10:42:17

-1

不知道它是否是最好的解決方案,但我發現解決方案工作完美。

我們需要在文件中寫入引用地址並重定向,我們需要從該文件讀取。首先我們需要加載文件助手。

$this->load->helper('file'); 

if ($this->form_validation->run()) 
{ 
    redirect(read_file('referrer.php')); 
} 
else 
{ 
    $referrer = $this->agent->referrer(); 
    //need to check wrong input submission and page refresh 
    if ($referrer != "http://localhost/CIpractice2/testing" && !empty($referrer)) 
     { 
      write_file('referrer.php', $referrer); 
     } 
    //show the form 
} 

請參考CodeIgniter的file helper文檔

+0

會話應該是首選 - 對於一個文件,同時發生的用戶會互相干擾 – Richard 2016-09-30 15:56:28

0

所有你需要的是:

所有的
redirect($_SERVER['HTTP_REFERER']);