2012-05-02 131 views
0

我想實現使用jQuery UI和笨2一個簡單的自動完成腳本,但我的模型不斷告訴我有一個未定義的變量,所以我不知道如果我的設置是正確的。jQuery UI的自動完成和笨

我的觀點

$(function() { 
    $("#txtUserSuburb").autocomplete({ 
     source: function(request, response){ 
     $.ajax({ 
      url: "autocomplete/suggestions", 
      data: { 
       term: $("#txtUserSuburb").val() 
      }, 
      dataType: "json", 
      type: "POST", 
      success: function(data){ 
       response(data); 
      } 
     }); 
     }, 
     minLength: 2 
    }); 
}); 

我控制器

function suggestions(){ 
    $this->load->model('autocomplete_model'); 
    $term = $this->input->post('term', TRUE); 
    $rows = $this->autocomplete_model->getAutocomplete($term); 
    echo json_encode($rows); 
} 

我的模型

function getAutocomplete() { 
    $this->db->like('postcode', $term, 'after'); 
    $query = $this->db->get('tbl_postcode'); 
    $keywords = array(); 
    foreach($query->result() as $row){ 
     array_push($keywords, $row->postcode); 
    }   
    return $keywords; 
} 

;隨行除了它的任何錯誤似乎不是$項變量被傳遞給模型。

+0

你的模型方法「getAutocomplete」沒有一個名爲「$術語」參數。 – mbh

+0

你知道jquery autocomplete內置了對遠程數據源的支持嗎?不需要用你自己的AJAX請求重新發明輪子。 –

回答

3

是的,我想你需要getAutocomplete()有一個參數 「$術語」:在阿賈克斯

function getAutocomplete($term) { 
+0

我試過添加,但然後查詢返回所有記錄,所以我不認爲值是從我的控制器傳遞給模型。我可以看到它從視圖傳遞給控制器​​。 – puks1978

+0

你可以在getAutocomplete()裏面測試$ term的值嗎?只要做一個print_r($ term);在$ this-> db-> like行之前,看看這個值是什麼。如果$ term爲空,查詢肯定會返回所有結果。 – continuum

0

後變化值在控制器

$(function() { 
    $("#txtUserSuburb").autocomplete({ 
     source: function(request, response){ 
     $.ajax({ 
      url: "autocomplete/suggestions", 
      data: { 
       term: request.term //change post value 
      }, 
      dataType: "json", 
      type: "POST", 
      success: function(data){ 
       response(data); 
      } 
     }); 
     }, 
     minLength: 2 
    }); 
}); 

設置頁面標題爲JSON

function suggestions(){ 
    $this->load->model('autocomplete_model'); 
    $term = $this->input->post('term', TRUE); 
    $rows = $this->autocomplete_model->getAutocomplete($term); 
    $this->output 
     ->set_content_type('application/json') 
     ->set_output(json_encode($rows)); 
}