【问题标题】:CakePhp Ajax AutocompleteCakePhp Ajax 自动完成
【发布时间】:2013-03-28 15:24:24
【问题描述】:

我正在尝试为 CakePhp 2.x 中的文本框设置 Ajax 自动完成功能。

在我看来,我有:

<?php $this->start('script'); ?>
<script type="text/javascript">
    $(document).ready(function () {
        var options, a;
        jQuery(function() {
            options = { 
                serviceUrl: "<?php echo $this->Html->Url(array('Controller' => 'Logs', 'action' => 'autoComplete')); ?>",
                minChars: 2,
            };
            a = $('#LogTimeSpent').autocomplete(options);
        });
    });
    $('#saveCust').click(function () {
        alert("Test")
    });
</script>
<?php $this->end(); ?>

在我的控制器中,我有:

function autoComplete($query) {
    if ($this->request->is('ajax'))
    {
        $suggestions = $this->Customer->find('all', array(
            'conditions' => array(
                'Customer.fullName LIKE' => '%'.$query.'%'
                )
            ));
        return json_encode(array('query' => $query, 'suggestions' => $suggestions));

    }
}

如果影响查询,Customer.fullName 是一个虚拟字段。 Firebug 目前给我一个 500 内部服务器错误。

【问题讨论】:

    标签: jquery jquery-autocomplete cakephp-2.1 json


    【解决方案1】:

    我发现您必须做一些特殊的事情才能使虚拟字段起作用。我决定虚拟字段不是要走的路,所以我更新了它。 $query 作为参数也是不正确的,我需要从$this-&gt;params['url']['query']; 获取查询字符串。最后,我需要使用_serialize,而不是返回json_encode。这是我更新的控制器,所以希望这会对某人有所帮助。我的观点在原帖中是正确的。

    function autoComplete() {
        if ($this->request->is('ajax'))
        {
            $query = $this->params['url']['query'];
            $this->set('query', $query);
    
            $customer = $this->Log->Customer->find('all', array(
                'conditions' => array(
                    'OR' => array(
                        'Customer.first_name LIKE' => '%'.$query.'%',
                        'Customer.last_name LIKE' => '%'.$query .'%'
                    )),
                'fields' => array(
                    'Customer.first_name', 'Customer.last_name'
                    )
                ));
    
            $names = array();
            $id = array();
            foreach ($customer as $cust) {
                $fullName = $cust['Customer']['last_name'] . ', ' . $cust['Customer']['first_name'];
                array_push($names, $fullName);
                array_push($id, $cust['Customer']['id']);
            }
            $this->set('suggestions', $names);
            $this->set('data', $id);
            $this->set('_serialize', array('query', 'suggestions', 'data'));        
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多