2016-11-16 81 views
1

每一個。我正在嘗試進行自動填充搜索,但它無法正常工作。 當用戶在搜索欄中寫入數據時,數據通過表中的一列進行。 這裏是代碼: 查看:搜索欄中的自動完成功能使用codeigniter

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Welcome to CodeIgniter</title> 


</head> 
<body> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
<script type="text/javascript" src="js/script.js"></script> 
<script> 
$("#country_id").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
      url: "http://localhost/new/index.php/travels/search_fields", 
      data: { term: $("#country_id").val()}, 
      dataType: "json", 
      type: "POST", 
      success: function(data){ 
       var resp = $.map(data,function(obj){ 
        return obj.tag; 
       }); 

       response(resp); 
      } 
     }); 
    }, 
    minLength: 2 
}); 
</script> 

<form> 
<input type="text" name="country_id" id="country_id" >     
</form> 
</body> 
</html> 

型號:

public function search_field($country_id){ 
$q= $this->db->query("select()->from('travels_detail')->where('destination', $country_id"); 
     echo json_encode($q->result_array()); 

    } 

控制器:

public function search_fields(){ 
     $destination= $this->input->post('country_id'); 
     $this->travel->search_field($country_id); 
} 

回答

0

在模型中的活動查詢是錯誤的$this->db->query("select()->from('travels_detail')->where('destination', $country_id");,和你都在積極錯過->get()查詢。

關注婁這樣的:

public function search_field($country_id){ 
    $q = $this->db->select("*")->from('travels_detail')->where('destination', $country_id)->get(); 
    echo json_encode($q->result_array()); 
} 

,或者

public function search_field($country_id){ 
    $this->db->select("*"); 
    $this->db->from('travels_detail'); 
    $this->db->where('destination', $country_id); 
    $q = $this->db->get(); 
    echo json_encode($q->result_array()); 
} 

在控制器代替$destination$country_id

您在AJAX調用這樣data: { term: $("#country_id").val()},term崗位價值,但你在控制器調用$this->input->post('country_id');

因此,在控制器$country_id = $this->input->post('term');

所以,你的控制器:

public function search_fields(){ 
    $country_id = $this->input->post('term'); 
    $this->travel->search_field($country_id); 
} 
+0

是啊,我改變了模式,但它顯示空數組 –

+0

我已經編輯我的答案。在控制器而不是'$ destination'到'$ country_id' –

+0

我編輯了我的答案,請刷新你的頁面。 –