2013-01-02 34 views
2

我嘗試實現從數據表中獲得的CakePHP 2.1數據自動完成CakePHP的2.1和jQuery UI自動完成沒有成功,請幫我不工作

在默認佈局

echo $this->Html->script('jquery-1.8.3'); 
    echo $this->Html->script('jquery-ui-1.9.2.custom'); 

在視圖文件

$('.TextBox').keydown(function (e){ 
    var FieldId = $(this).attr('id'); 
    var ColName = $(this).attr('title'); 
    var table = document.getElementById("dbTable").value; 
    var TableName = table + "_docs"; 
    var TextValue = "" 

    if (e.which >= 32 || e.which < 127) { 
     var c = String.fromCharCode(e.which); 
     TextValue = $(this).val() + c; 
     } 

    if(TextValue != ""){ 
       $.ajax({ 
       type:'POST', 
       url:"../AutoSearch/" + TableName + "/" + ColName + "/" + TextValue , 
       success:function(response){ 
       var data = response.split("|"); 
       $('#' + FieldId).autocomplete(data); 
       } 
     }); 
     } 
    }); 

in controller

public function AutoSearch($table,$col,$text){ 
     $this->autoRender=false; 
     if($this->RequestHandler->isAjax()){ 
     Configure::write('debug', 0); 
     if(trim($text) != ""){ 
      $info = ""; 
      $info = $this->Template->getAutoComplete($table,$col,$text); 
      } 
     else 
     { 
      $info = ""; 
     } 
     return $info; 
     } 
    } 

在模型

 public function getAutoComplete($table,$col,$text){ 
      $sql = "select " . $col . " from " . $table . " where " . $col . " Like '%" . $text . "%'"; 
      $ret = $this->query($sql); 
      $rText = ""; 
      foreach($ret as $val){ 
       if($rText == ""){ 
        $rText = $val[$table][$col] . "|";} 
        else { 
       $rText = $rText . $val[$table][$col] . "|";} 
      } 
       return $rText; 
    } 

錯誤消息的螢火

類型錯誤:this.source不是函數

。適用(例如,參數);

+0

通過做這種方式,你正在你的應用程序容易受到攻擊。您可以根據用戶輸入提供自定義的查詢參數。 – icebreaker

回答

1

作爲出發點,我會建議使用默認jQuery自動完成http://jqueryui.com/autocomplete/並查找類似的內容。

在意見

$('.TextBox').autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       type:'POST', 
       url:"/your_controller/your_action/", 
       data: { 
        column: 'col', 
        search: request.term // request.term will have value in field 
       }, 
       success:function(response){ 
        // to see what you are getting to browser 
        // console.log(response); 
        response($.map(response, function(item) { 
         // depending on what you send, return object you need 
         // label will be shown in list, value will be set when selected 
         return { 
          label: item.name, 
          value: item.id 
         } 
        })); 
       } 
       } 
      }); 
     } 
    }); 

在控制器

public function your_action() { 
    // to see what you are getting to controller 
    // debug($this->request->data); 
    exit(json_encode($this->YourModel->find('list', array('conditions' => array()))); 
} 
+0

有時我使用不同的表格,從控制器和模型響應是好的我可以看到螢火蟲,但沒有下拉列表 – user1943201

+0

我是cakephp和jquery的新手,但我已完成dms所有其他工作正常我需要自動完成破冰船清除線請 – user1943201

+0

看看編輯的代碼是否有幫助 – icebreaker