2011-01-24 29 views
2

我有一個名爲「項目」的表格,我希望能夠搜索。我寧願使用現有的方法來調用模型來獲取查詢結果。所以我剛纔的URL格式是example.com/projects/id/slug,對於所有的項目只有example.com/projects。我想要一個將關鍵字作爲字符串傳遞給方法的搜索表單。

我知道CI不允許默認$ _GET:

從CodeIgniter的手冊有關安全:

GET,POST和COOKIE數據

GET數據被簡單地禁止 CodeIgniter自從系統利用 URI段而不是傳統的 URL查詢字符串(除非在y中啓用了 查詢字符串選項 我們的配置文件)。在系統初始化期間,全局GET陣列被輸入類 取消設置。

我的問題是我如何使用這種方式與多個關鍵字的URI段?

我可以做類似搜索/關鍵字+ secondkeyword + thirdkeyword的內容嗎?

使用表單是否有從文本框中獲取關鍵字到上述格式?

感謝,

比利

回答

3

如果你想那樣做......

你可能只是做這樣的事情,假設有多個輸入後,他們只對搜索,它可能是這個樣子

function search(){ 

    $url = $this->uri->segment(2); 

    if(empty($url)){ 
     if((isset($_POST) && (!empty($_POST)) 
     { 
     $search_seg = ''; 

     foreach($_POST as $k => $v){ 
      // I always make sure to use the CI post w/ 
      // TRUE set in the second param so as to XSS filter the user input 
      $var = $this->input->post($k, TRUE); 
      // Just incase the user input had a plus in it? 
      $var = str_replace('+', '%20', $var) 
      // Concatenate the search string 
      $search_seg .= $var . '+'; 
     } 

     // Make the url, use substr() to strip the last + off the end 
     $search_seg = 'search/' . substr($search_seg, 0, -1); 

     /* Make sure CI's URL helper is enabled 
      $this->load->helper('url'); if it hasn't been loaded 
      This will give the illusion that the form post went to this URL, 
      thus doing what you're looking for... */ 
     redirect($search_seg, 'location'); 

     }else{ 
     // There was no post, do whatever 
     } 
    }else{ 
     $search_arr = explode('+', $url); 
    } 

以上應該做你描述的正是相當多,雖然有一些方法來重新創建$ _GET數組,並仍與CI風格網址的使用它們,儘管這是一個小更復雜

其他信息:

如果只有一個搜索輸入字段,並且這些條款之間用空格分隔,那麼您可能希望這樣做(可能有一些正則表達式過濾)...這種替換foreach($_POST as $k => $v)...循環:如果你希望你的URL是這樣

$keywordinput = $this->input->post('keywords', TRUE); 
$keywordinput = trim($keywordinput); 

$keywords = explode(' ', $keywordinput); 

foreach($keywords as $word){ 
    if(!empty($word)){ 
     $word = str_replace('+', '%20', $var) 
     $search_seg .= $word . '+'; 
    } 
} 
+0

感謝,我將不得不在這個 – iamjonesy 2011-01-27 12:30:16

0

使用$ _ POST可能是複雜的查詢一個更好的選擇,但是這可能工作,但需要URI有參數特定的順序(可能有更好的方法)

/*controller/method/params = search/do_search/Ross/Red/Male */ 

function do_search($name, $colour, $gender) 
{ 
    $this->db->or_where('name', $name); 
    $this->db->or_where('colour', $colour); 
    $this->db->or_where('gender', $gender); 
    // etc 
} 

不是很可擴展或靈活,但是對於簡單搜索它可能是不夠的。

0

-

search/keyword+secondkeyword+thirdkeyword? 

,也希望它成爲可收藏,然後使用JavaScript是唯一的選擇我猜。

使用JavaScript可以#後設置URL搜索參數,所以最終的URL將是這樣的 -

search#keyword+secondkeyword+thirdkeyword 

如果你使用這種方法,這意味着你將加載通過Ajax即每個搜索結果當遇到一個url時,你會得到搜索關鍵字後哈希從URL的URL。通過ajax加載結果並顯示結果。如果搜索條件發生了變化,那麼每次需要使用JavaScript在散列之後將新關鍵字追加到URL時。

基本的JavaScript代碼來獲取參數的URL後#是如下 -

var parameters = window.location.hash; 
相關問題