【问题标题】:autocomplete search form cakephp自动完成搜索表单 cakephp
【发布时间】:2011-08-29 15:12:11
【问题描述】:

你好,我是个新手,我正在寻找一种方法,让搜索框像谷歌一样具有自动完成功能。

我已经搜索过,我发现的最佳前景似乎是我在论坛上找到的http://www.pengoworks.com/workshop/jquery/autocomplete.htm。建议它的人说他将它与http://code.google.com/p/searchable-behaviour-for-cakephp/ 一起使用,因为我在最后一次尝试找出 cakephp 时设法安装了 searchable。

问题是,我以前没有使用过多的 javascript,而且我对我到底要做什么有点困惑。带有自动完成代码的文档没有详细介绍我能理解的任何细节。

如果我们假设我设法正确安装了可搜索的行为,任何善良的人都可以向我解释我将如何让自动完成功能发挥作用吗?

它说只使用:

$("selector").autocomplete(url [, options]);

例如:

$("#input_box").autocomplete("autocomplete_ajax.cfm");

自动完成功能需要一个 id 为“input_box”的输入元素存在。当用户开始在输入框中输入内容时,自动完成程序将使用名为 q 的 GET 参数请求 autocomplete_ajax.cfm

这就是我不明白的一点。我打算把它放在哪里?一旦我把它放在某个地方,我是否只需将我的输入之一命名为“input_box”?

提前致谢。

【问题讨论】:

标签: php search cakephp autocomplete


【解决方案1】:

echo $this->Html->scriptBlock(

'$("#FooBarField").autocomplete({'

    .'source:"/Search/find",'
    .'delay: 100,'
    .'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},'
    .'open:function(event,ui){$(this).parent().parent().children("input").val(0);}'

.'});'.

array('inline' => false));

【讨论】:

  • 实际上是 damusnet 答案的副本(至少是其中的一部分)。
【解决方案2】:

分为三个步骤:

1) 使用视图中的 Html 帮助器创建一个带有输入字段的完全正常的表单:

// app/views/foo_bars/search.ctp
<?php
echo $this->Form->create('FooBar');
echo $this->Form->input('field');
echo $this->Form->end('Submit');
?>

2) 触发 jquery 自动完成功能:

// app/views/foo_bars/search.ctp
<?php
echo $this->Html->scriptBlock(
    .'$("#FooBarField").autocomplete({'
        .'source:"/foo_bars/find",'
        .'delay: 100,'
        .'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},'
        .'open:function(event,ui){$(this).parent().parent().children("input").val(0);}'
    .'});'
    array('inline' => false));
?>

3) 通过控制器查询数据库以获得可能的值:

// app/controllers/foo_bars_controller.php
<?php
public function find() {
    if ($this->RequestHandler->isAjax()) {
        $this->autoLayout = false;
        $this->autoRender = false;
        $this->FooBar->recursive = -1;
        $results = $this->FooBar->find('all', array('fields' => array('id', 'name'), 'conditions' => array('name LIKE "%'.$_GET['term'].'%"')));
        $response = array();
        $i = 0;
        foreach($results as $result){
            $response[$i]['value'] = $result['FooBar']['name'];
            $response[$i]['id'] = $result['FooBar']['id'];
            $i++;
        }
        echo json_encode($response);
    }
}
?>

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多