最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Bootstrap 2.2.1 Typeahead - Stack Overflow

matteradmin9PV0评论

PHP, returns a JSON encoded array

$this->load->model('car_model', 'cars');
$result = $this->cars->searchBrand($this->input->post('query'));
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
$output = array();
foreach($result as $r)
    $output['options'][$r->brandID] = $r->brandName;
print json_encode($output);

Outputs: {"options":{"9":"Audi","10":"Austin","11":"Austin Healey"}}

JS updated:

$(".searchcarBrands").typeahead({
    source: function(query, typeahead) {
        $.ajax({
            url: site_url + '/cars/search_brand/'+query,
            success: function(data) {
                typeahead.process(data);
            },
            dataType: "json"
        });
    },
    onselect: function(item) {
        $("#someID").val(item.id);
    }
});

UPDATE: Uncaught TypeError: Object function (){return a.apply(c,e.concat(k.call(arguments)))} has no method 'process'

If I type just 'A' then typeahead shows me only the first letter of each result (a bunch of A letters). If I type a second letter I see nothing anymore.

I've tried JSON.parse on the data or using data.options but no luck.

What am I doing wrong?

PHP, returns a JSON encoded array

$this->load->model('car_model', 'cars');
$result = $this->cars->searchBrand($this->input->post('query'));
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
$output = array();
foreach($result as $r)
    $output['options'][$r->brandID] = $r->brandName;
print json_encode($output);

Outputs: {"options":{"9":"Audi","10":"Austin","11":"Austin Healey"}}

JS updated:

$(".searchcarBrands").typeahead({
    source: function(query, typeahead) {
        $.ajax({
            url: site_url + '/cars/search_brand/'+query,
            success: function(data) {
                typeahead.process(data);
            },
            dataType: "json"
        });
    },
    onselect: function(item) {
        $("#someID").val(item.id);
    }
});

UPDATE: Uncaught TypeError: Object function (){return a.apply(c,e.concat(k.call(arguments)))} has no method 'process'

If I type just 'A' then typeahead shows me only the first letter of each result (a bunch of A letters). If I type a second letter I see nothing anymore.

I've tried JSON.parse on the data or using data.options but no luck.

What am I doing wrong?

Share Improve this question edited Nov 6, 2012 at 15:32 stef asked Nov 6, 2012 at 13:48 stefstef 27.8k31 gold badges107 silver badges143 bronze badges 2
  • Are you essentially attempting to convert typeahead to allow a remote data source? – Darrrrrren Commented Nov 6, 2012 at 13:55
  • OK, see my answer - I believe my code should help you. – Darrrrrren Commented Nov 6, 2012 at 14:00
Add a ment  | 

3 Answers 3

Reset to default 3

I've been battling this for the last day with Bootstrap 2.2.1. No matter what I did, it would not work. For me, I always got the process undefined error unless I put a breakpoint in the process function (maybe just because FireBug was open?).

Anyway, as a patch I re-downloaded Bootstrap with typeahead omitted, got the typeahead from here: https://gist.github./2712048

And used this code:

$(document).ready(function() {
    $('input[name=artist]').typeahead({
        'source': function (typeahead) {
            return $.get('/7d/search-artist.php', { 'artist': typeahead.query }, function (data) {
                return typeahead.process(data);
            });
        },
        'items': 3,
        'minLength': 3
    },'json')
});

My server returns this (for 'Bo'):

["Bo","Bo Burnham","Bo Diddley","Bo Bruce","Bo Carter",
 "Eddie Bo","Bo Bice","Bo Kaspers Orkester","Bo Saris","Bo Ningen"]

Of course, now it ignores my minLength, but it will get me through the day. Hope this helps.

EDIT: Found the solution here: Bootstrap 2.2 Typeahead Issue

Using the typeahead included with Bootstrap 2.2.1, the code should read:


    $(document).ready(function() {
        $('input[name=artist]').typeahead({
            'source': function (query,typeahead) {
                return $.get('/search-artist.php', { 'artist': encodeURIComponent(query) }, function (data) {
                    return typeahead(data);
                });
            },
            'items': 3,
            'minLength': 3
        },'json')
    });

Here's what I do to facilitate remote data sources with bootstrap's typeahead:

$("#search").typeahead({

    source: function(typeahead, query) {

        $.ajax({

            url: "<?php echo base_url();?>customers/search/"+query,
            success: function(data) {

                typeahead.process(data);
            },
            dataType: "json"
        });
    },
    onselect: function(item) {

        $("#someID").val(item.id);
    }
});

And then you just need to make sure your JSON-encoded arrays contain a value index for the label and an id field to set your hidden id afterwards, so like:

$this->load->model('car_model', 'cars');
$brands = $this->cars->searchBrand($this->uri->segment(4));
$output = array();
foreach($brands->result() as $r) {

    $item['value'] = $r->brandName;
    $item['id']    = $r->brandID;
    $output[] = $item;
}
echo json_encode($output);
exit;

$.post is asynchronous, so you can't user return in it. That doesn't return anything.

Post a comment

comment list (0)

  1. No comments so far