Codeigniter和Typeaheadjs - 问题

时间:2014-02-07 19:37:40

标签: codeigniter-2 typeahead.js bloodhound

我对CI和Typeahead有一些问题,我没有得到任何结果; /

JS

var countries = new Bloodhound({
  datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name); },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  limit: 10,
  prefetch: {
    url: base_url + 'home/search?q=%QUERY',
    filter: function(list) {
      return $.map(list, function(country) { return { name: country }; });
    }
  }
});

countries.initialize();

$('.typeahead').typeahead(null, {
  name: 'countries',
  displayKey: 'name',
  source: countries.ttAdapter()
});

CI控制器

public function search(){
    $query = $this->home_model->getData();
    echo json_encode($query);
}

CI模型

private $_cityTable = 'city';

public function getData(){
    $city = $this->input->get('q');
    $query = $this->db->select('city_name')->like('city_name', $city, 'after')->get($this->_cityTable);
    foreach ($query->result_array as $key) {
        $array[] = $key['city_name'];
    }
    return $array;
}

并查看

<input type="text" class="typeahead">

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

当我调试this示例时,我发现传递给过滤器函数的parsedResponse对象具有以下结构:

parsedResponse ={page: x, results:[], total_pages:x, total_results: x};

在哪里&#39; x&#39;是一个整数。

因此,要使代码工作,请更改过滤器函数,以便遍历列表对象中的结果数组,即

filter: function(list) {
 return $.map(list.results, function(country) { return { name: country }; });
}