2014-01-23 63 views
0

我是jquery的新手,並且遇到了自動完成功能問題。編輯:我應該提到我正在使用MVC與Codeigniter。我的AJAX響應返回像這樣[{"customer_name":"Adecco Management & Consulting S.A."}]。它也不是全部連續它是像這樣的下拉中的每個字符在Codeigniter中爲jquery自動完成返回響應正確

[ 
{ 
" 
c 
u 
s 
t 

等等。這是我的自動完成腳本。

$('#cust_name').autocomplete({ 
    source: function(request,response){ 
     var request = { 
      toSearch: $('#cust_name').val() 
     }; 
     $.ajax({ 
      url: '/researchDB/index.php/rdb_con/autoComplete', 
      data: request, 
      datatype:"json", 
      type: 'POST', 
      success: function(data){ 
       response(data); 
      } 
     }); 
    } 
}); 

和我的控制器:

function autoComplete(){ 
    $data['id'] = $this->rdb_mod->autoComplete(); 
    echo json_encode($data['id']); 
} 

型號:鑑於

public function autoComplete(){ 
     $toSearch = $_POST['toSearch']; 
     $this->db->select('customer_name'); 
     $this->db->like('customer_name', $toSearch, 'after'); 
     $query = $this->db->get('research'); 
     return $query->result(); 
    } 

輸入:

<input data-input-type="cust_name" id="cust_name" class="ids form-control search-query " type="text" name="customer_name"> 

我不知道我成立了jQuery功能正常,但該響應包括期望的結果,格式錯誤,當我輸入輸入時。謝謝你提供的所有幫助!

+1

你的問題不完整或是我嗎?我沒有看到第二行代碼中的任何內容。 –

+0

是的。我打入標籤輸入並過早張貼。 – vizyourdata

+0

@AgashThamo。一定是你。我個人認爲這很清楚,更新之前首選的問題... – NewInTheBusiness

回答

0

我收到了SO之外的答案,並希望將解決方案發布給其他人。

控制器:我需要將結果放入一個數組,並將其作爲一個對象傳遞給ajax響應。

function autoComplete(){ 
     $data['id'] = $this->rdb_mod->autoComplete(); 
     $results = array(); 
     foreach($data['id'] as $row){ 
      $results[]=$row->customer_name; 
     } 
     echo json_encode($results); 
} 

的jQuery:據我瞭解這部分,我沒有利用內置的函數,因此覆蓋請求變量自動完成設置。

$('#cust_name').autocomplete({ 
     source: function(request,response){ 
      $.ajax({ 
       url: '/researchDB/index.php/rdb_con/autoComplete', 
       data: request, 
       datatype:"json", 
       type: 'POST', 
       success: function(data){ 
        var items = JSON.parse(data); 
        response(items); 
       } 
      }); 
    } 
    }); 

模型:沒有太大變化。我添加了不同的限制dup值。

public function autoComplete(){ 
     $toSearch = $_POST['term']; 
     $this->db->distinct(); 
     $this->db->select('customer_name'); 
     $this->db->like('customer_name', $toSearch, 'after'); 
     $query = $this->db->get('research'); 
     return $query->result(); 
    } 

感謝所有幫助過我的人!