2

我有一个应用程序,其中包含一个名为项目的表,我希望能够在该表上进行搜索。我更喜欢使用现有的方法来调用模型来获取查询结果。所以我刚才的 URL 格式是 example.com/projects/id/slug,对于所有项目来说,只是 example.com/projects。我想要一个将关键字作为字符串传递给方法的搜索表单。

我知道 CI 默认不允许 $_GET :

来自 CodeIgniter 的安全手册:

GET、POST 和 COOKIE 数据

CodeIgniter 根本不允许 GET 数据,因为系统使用 URI 段而不是传统的 URL 查询字符串(除非您在配置文件中启用了查询字符串选项)。全局 GET 数组在系统初始化期间由 Input 类取消设置。

我的问题是如何以这种方式将 URI 段与多个关键字一起使用?

我可以做一些类似搜索/关键字+第二个关键字+第三个关键字的事情吗?

无论如何使用表单将关键字从文本框中获取到上述格式?

谢谢,

比利

4

3 回答 3

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 样式 URL 一起使用,尽管这有点复杂

附加信息:

如果只有一个搜索输入字段,并且例如,这些术语由空格分隔,那么您可能想要这样做(可能有一些正则表达式过滤)......foreach($_POST as $k => $v)...用这个替换循环:

$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 . '+';
    }
}
于 2011-01-24T17:14:10.223 回答
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
}

不是很可扩展或灵活,但对于简单的搜索可能就足够了。

于 2011-01-24T15:11:38.910 回答
0

如果您希望您的网址是这样的 -

search/keyword+secondkeyword+thirdkeyword? 

并且还希望它可以加入书签,然后使用 javascript 是我猜的唯一选择。

使用 javascript,您可以在 # 之后在 url 中设置搜索参数,因此最终的 url 将是这样的 -

search#keyword+secondkeyword+thirdkeyword

如果您使用这种方法,这意味着您将通过 ajax 加载搜索结果,即每次遇到 url 时,您将通过 javascript 从 url 哈希后获取搜索关键字。通过ajax加载结果并显示结果。如果更改了搜索条件,那么每次您需要使用 javascript 在哈希后将新关键字附加到 url。

#之后获取url中参数的基本javascript代码如下 -

var parameters = window.location.hash;
于 2011-01-24T18:07:55.803 回答