自动完成搜索表单 cakephp


autocomplete search form cakephp

嘿,我是一个完全的新手,我正在寻找一种方法来像谷歌一样拥有一个带有自动完成功能的搜索框。

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

问题是,我

以前没有使用过太多的javascript,我对我到底要做什么有点困惑。带有自动完成代码的文档没有涉及我能理解的任何细节。

如果我们假设我设法正确安装了可搜索的行为,那么任何好心的人都可以向我解释我将如何使自动完成工作吗?

它说只使用:

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

例如:

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

自动完成需要存在 ID 为"input_box"的输入元素。当用户开始在输入框中键入时,自动完成器将使用名为 q 的 GET 参数请求autocomplete_ajax.cfm

这就是我没有得到的一点。我应该把它放在哪里?一旦我把它放在某个地方,那么我只需要命名我的一个输入" input_box "?

提前谢谢。

有三个步骤:

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

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