【问题标题】:Cakephp3 jQuery autocompleteCakephp3 jQuery 自动完成
【发布时间】:2016-07-05 13:34:07
【问题描述】:

我是 CakePHP3 (+stackoverflow) 的新手,并尝试实现自动完成功能。我想将自动完成功能附加到我的 index.ctp 中的搜索输入。

  1. 请求返回所有汽车对象(忽略 get.term)
  2. 响应未附加到搜索输入

得到一些帮助会很好 - 谢谢!

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');
    }
}

【问题讨论】:

    标签: jquery ajax autocomplete cakephp-3.0


    【解决方案1】:

    好的,我刚刚找到了一个解决方案(可能并不完美?!)。这是我的代码

    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);   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2011-09-10
      • 2013-01-14
      相关资源
      最近更新 更多