2011-01-24 77 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;