开发者

jQuery UI autocomplete + CakePHP

开发者 https://www.devze.com 2023-01-16 23:59 出处:网络
I\'m setting up jQuery UI autocomplete on a CakePHP site, and feel like I\'m missing something really obvious, but it\'s almost working...

I'm setting up jQuery UI autocomplete on a CakePHP site, and feel like I'm missing something really obvious, but it's almost working...

So the simple jQuery code is:

$(f开发者_StackOverflow中文版unction() {
    $("#SearchQuery").autocomplete({
        source: "<?= $session->base ?>/search/complete",
        minLength: 2
    });
});

This connects to my search controller, and the search controller returns items from the database. I can get the results back if I don't try to actually look at the "term" (what has been typed. So, in my controller this works:

function complete(){
    $entries = $this->Entry->find('list');
    $this->set('entries', $entries);
}

It is returned as JSON, and drops down from the input like it should. But it never narrows the results based on what has been typed. I would think that this should narrow the results:

function complete($query = null){
    $entries = $this->Entry->find('list', 
        array('conditions' => array('title LIKE' => '%'.$query.'%')));
    $this->set('entries', $entries);
}

But with this code nothing is ever returned. What am I doing wrong?

P.S. People who find this question and are having trouble getting the results back to the autocomplete function, be sure you're returning properly formatted JSON results: http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/


The answer is pretty simple, as expected... "term" is passed as $_GET['term'], so it's not available from the controller function's variables. (Why I thought it would be passed as a URL segment I have no idea...)

This works:

function complete(){
    $query = $_GET['term'];

    $entries = $this->Entry->find('list', 
        array('conditions' => array('title LIKE' => '%'.$query.'%')));
    $this->set('entries', $entries);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号