如何在php codeigniter自动完成中搜索该字母

时间:2014-04-03 08:39:38

标签: php codeigniter

在我的php codeigniter项目中使用自动完成选项。它基于数据库的第一个字母进行过滤。现在我想搜索那一列中出现的那封信。

使用代码从数据库中获取数据 Ajax的

$(document).ready(function() {
   $(function() {
        $( "#category" ).autocomplete({
            source: function(request, response) {
                $.ajax({ url: base_url+"/suggest/get_category",
                data: { term: $("#category").val()},
                dataType: "json",
                type: "POST",
                success: function(data){
                    response(data);
                }
            });
        },
        minLength: 2
        });
    });

控制器

function get_category()
{
    $term = $this->input->post('term');

    if (strlen($term) < 2) break;

    $rows = $this->suggest->GetAutocomplete(array('keyword' => $term));

    $json_array = array();
    foreach ($rows as $row)
         array_push($json_array, $row->category_name);

    echo json_encode($json_array);
}

模型

function GetAutocomplete($options = array())
    {
        $this->db->select('category_name');
        $this->db->like('category_name', $options['keyword'], 'after');
        $query = $this->db->get('category');
        return $query->result();
    }

提前多多感谢。

3 个答案:

答案 0 :(得分:0)

    $options=$this->input->get('term');     
    $this->db->like('category_name',$options);          
    $query=$this->db->get('category');
    $result=$query->result();
    $names=array();
    foreach($result as $row)
    {
        $val=array();
        $val['label']=$row->category_name;
        $val['value']=$row->category_name;
        array_push($names,$val);
    }
    echo json_encode($names);

答案 1 :(得分:0)

迟到,您可以更改$ this-&gt; db-&gt; like(),因为您已经在&#39;之后传递参数&#39;所以你需要用'&& 39;'替换第三个参数。关键字,

根据CI-Active Record文档, 如果要控制放置通配符(%)的位置,可以使用可选的第三个参数。您的选择是在&#39;之后,&#39;之后&#39;和&#39;两个&#39; (这是默认值。)

$this->db->like('title', 'match', 'before'); 
// Produces: WHERE title LIKE '%match'  

$this->db->like('title', 'match', 'after'); 
// Produces: WHERE title LIKE 'match%' 

$this->db->like('title', 'match', 'both'); 
// Produces: WHERE title LIKE '%match%'

有关详细信息,请访问http://ellislab.com/codeigniter/user-guide/database/active_record.html

function GetAutocomplete($options = array())
{
    $this->db->select('category_name');
    $this->db->like('category_name', $options['keyword'], 'both');
    $query = $this->db->get('category');
    return $query->result();
}

谢谢,

答案 2 :(得分:-1)