2016-07-05 7 views
0

私はCakePHP3(+ stackoverflow)を初めて使い、オートコンプリートを実装しようとしています。私はindex.ctp内のsearchinputにオートコンプリート関数をつけたいと思っています。Cakephp3 jQueryオートコンプリート

  1. 要求は、いくつかの助けを得るために大丈夫だと思う、すべての車のオブジェクト(get.termを無視します)
  2. 応答がsearchinput

に接続されていないを返します - 感謝を!

index.ctp

<?php 
echo $this->Form->create('Cars'); 
    echo $this->Form->input('name', [ 
      'label' => 'Search', 
      'id' => 'autocomplete', 
      'class' => 'ui-autocomplete' 
    ]); 
echo $this->Form->button('Search', ['type' => 'submit']); 
echo $this->Form->end(); 
?> 
<script> 
$("#autocomplete").autocomplete(
    { 
     search: function() {}, 
     source: function (request, response) 
     { 
      $.ajax(
      { 
       source: "/cars/autocomplete", 
       dataType: "json", 
       data: 
       { 
        term: request.term, 
       }, 
       success: function (data) 
       { 
        response(data); 
        console.log(data); 
       } 
      }); 
     }, 
     minLength: 2 
    }); 
</script> 

CarsController.php

function autocomplete() { 
    if ($this->request->is('ajax','get')) { 
     $term = $this->request->data["term"]; 
     $terms = $cars->find('all', [ 
      'conditions' => ['Cars.name >' => $term], 
      'limit' => 10 
     ]); 

    $data = array(); 
     foreach($terms as $term) { 
      $row = $term->name; 
      array_push($data, $row); 
     } 

     // $this->layout = 'ajax'; 
     $this->set('terms', $terms); 
     echo json_encode($data); 
    // return json_encode($data); 
    } 
    else { 
     echo json_encode('Nothings found'); 
    } 
} 

答えて

0

さて、私は(ない完璧!?かもしれない)解決策を見つけました。ここに私のコードだ

index.ctp

<script> 
$(function() { 
$("#autocomplete").autocomplete({ 
    minLength: 1, 
    source: function(request, response) { 
     $.ajax({ 
      url: "<?php echo Router::url(['controller' => 'Cars', 'action' => 'autocomplete']);?>" + '?term=' + 
       request.term, 
       dataType: "json", 
       success: function (data) 
       { 
        response(data); 
        console.log(data); 
       } 
      }); 
     } 
    }); 
}); 
</script> 

CarsController.phpアクションの自動補完

public function autocomplete() { 
    $this->autoRender = false; 
    $terms = $this->Cars->find('list', array(
      'conditions' => array(
        'Cars.name LIKE' => trim($this->request->query['term']) . '%' 
      ) 
    )); 
    echo json_encode($terms); 
} 
関連する問題