Codeigniter自动完成搜索

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeigniter自动完成搜索相关的知识,希望对你有一定的参考价值。

example I used to create a auto suggest search from that pulls from a database. The example pulls from a single db table containing categories. Using jQueryUI made this pretty painless but by default the autocomplete feature uses GET variables and you must enable these in your Codeigniter settings to work properly. This example uses POST variables instead so the js is modified accordingly.
  1. // js code after document is ready
  2. // Search autocomplete
  3. $("#swSearch").autocomplete({
  4. minLength: 1,
  5. source: function(req, add){
  6. $.ajax({
  7. url: '/search', //Controller where search is performed
  8. dataType: 'json',
  9. type: 'POST',
  10. data: req,
  11. success: function(data){
  12. if(data.response =='true'){
  13. add(data.message);
  14. }
  15. }
  16. });
  17. }
  18. });
  19.  
  20.  
  21.  
  22.  
  23.  
  24. // Controller search function
  25.  
  26. $keyword = $this->input->post('term');
  27.  
  28. $data['response'] = 'false'; //Set default response
  29.  
  30. $query = $this->Mprofile->sw_search($keyword); //Model DB search
  31.  
  32. if($query->num_rows() > 0){
  33. $data['response'] = 'true'; //Set response
  34. $data['message'] = array(); //Create array
  35. foreach($query->result() as $row){
  36. $data['message'][] = array('label'=> $row->friendly_name, 'value'=> $row->friendly_name); //Add a row to array
  37. }
  38. }
  39. echo json_encode($data);
  40.  
  41.  
  42.  
  43. // Simple model example
  44.  
  45. public function sw_search($keyword)
  46. {
  47. $this->db->select('id, friendly_name');
  48. $this->db->from('business_category');
  49. $this->db->where('suppress', 0);
  50. $this->db->like('friendly_name', $keyword);
  51. $this->db->order_by("friendly_name", "asc");
  52.  
  53. $query = $this->db->get();
  54. foreach($query->result_array() as $row){
  55. //$data[$row['friendly_name']];
  56. $data[] = $row;
  57. }
  58. //return $data;
  59. return $query;
  60. }

以上是关于Codeigniter自动完成搜索的主要内容,如果未能解决你的问题,请参考以下文章

自动完成给出 codeigniter3 404 错误

如何将自动完成修复到与 Codeigniter 一起出现的两个数据库中?

如何使用带有codeigniter的数据库中的JQuery使用自动完成功能?

Codeigniter 助手重复 HTML 代码片段

我的 Codeigniter 使用 ajax 自动完成

我的自动完成功能在 codeigniter 中不起作用