twitter bootstrap typeahead ajax example

2019-01-01 09:35发布

I'm trying to find a working example of the twitter bootstrap typeahead element that will make an ajax call to populate it's dropdown.

I have an existing working jquery autocomplete example which defines the ajax url to and how to process the reply

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { minChars:3, max:20 };
    $("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

What do i need change to convert this to the typeahead example?

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
    var options = { source:'/index/runnerfilter/format/html', items:5 };
    $("#runnerquery").typeahead(options).result(
            function(event, data, formatted)
                {
                    window.location = "./runner/index/id/"+data[1];
                }
            );
       ..

I'm going to wait for the 'Add remote sources support for typeahead' issue to be resolved.

16条回答
一个人的天荒地老
2楼-- · 2019-01-01 10:02

I am using this method

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},
    {
    name: 'options',
    displayKey: 'value',
    source: function (query, process) {
        return $.get('/weather/searchCity/?q=%QUERY', { query: query }, function (data) {
            var matches = [];
            $.each(data, function(i, str) {
                matches.push({ value: str });
            });
            return process(matches);

        },'json');
    }
});
查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 10:03

I've augmented the original typeahead Bootstrap plugin with ajax capabilities. Very easy to use:

$("#ajax-typeahead").typeahead({
     ajax: "/path/to/source"
});

Here's the github repo: Ajax-Typeahead

查看更多
泪湿衣
4楼-- · 2019-01-01 10:06

Edit: typeahead is no longer bundled in Bootstrap 3. Check out:

As of Bootstrap 2.1.0 up to 2.3.2, you can do this:

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.get('/typeahead', { query: query }, function (data) {
            return process(data.options);
        });
    }
});

To consume JSON data like this:

{
    "options": [
        "Option 1",
        "Option 2",
        "Option 3",
        "Option 4",
        "Option 5"
    ]
}

Note that the JSON data must be of the right mime type (application/json) so jQuery recognizes it as JSON.

查看更多
何处买醉
5楼-- · 2019-01-01 10:07

I did some modifications on the jquery-ui.min.js:

//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...

// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....

// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`

and add following css

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}

Works perfect.

查看更多
不流泪的眼
6楼-- · 2019-01-01 10:09

I don't have a working example for you nor do I have a very clean solution, but let me tell you what I've found.

If you look at the javascript code for TypeAhead it looks like this:

items = $.grep(this.source, function (item) {
    if (that.matcher(item)) return item
  })

This code uses the jQuery "grep" method to match an element in the source array. I didn't see any places you could hook in an AJAX call, so there's not a "clean" solution to this.

However, one somewhat hacky way that you can do this is to take advantage of the way the grep method works in jQuery. The first argument to grep is the source array and the second argument is a function that is used to match the source array (notice Bootstrap calls the "matcher" you provided when you initialized it). What you could do is set the source to a dummy one-element array and define the matcher as a function with an AJAX call in it. That way, it will run the AJAX call just once (since your source array only has one element in it).

This solution is not only hacky, but it will suffer from performance issues since the TypeAhead code is designed to do a lookup on every key press (AJAX calls should really only happen on every few keystrokes or after a certain amount of idle time). My advice is to give it a try, but stick with either a different autocomplete library or only use this for non-AJAX situations if you run into any problems.

查看更多
春风洒进眼中
7楼-- · 2019-01-01 10:10

One can make calls by using Bootstrap. The current version does not has any source update issues Trouble updating Bootstrap's typeahead data-source with post response , i.e. the source of bootstrap once updated can be again modified.

Please refer to below for an example:

jQuery('#help').typeahead({
    source : function(query, process) {
        jQuery.ajax({
            url : "urltobefetched",
            type : 'GET',
            data : {
                "query" : query
            },
            dataType : 'json',
            success : function(json) {
                process(json);
            }
        });
    },
    minLength : 1,
});
查看更多
登录 后发表回答