Twitter's typeahead example / dynamic query

2019-08-24 02:49发布

I am searching for an example for twitter's typeahead.

I want to get the data with a function, should I use remote? The returned from the server data would be a Json (not simply an array). From those I want to display only the field e.g. name.

Upon selection of the correct name I want to run another function that e.g. alerts the id and the description (fields) of that object. Probably with typeahead:autocompleted event binder ?

Update/ sample:

The Dajaxice.async.get_closest_events() bellow sends 3 parameters to the internal server (lat,lng, query). Query is the value the users has written. It returns an array (venuesNames) which is going to be displayed in the dropdown.

$( "#locationQueryInput" ).typeahead({
    remote:{
        replace: function (query ) {
            //alert($("locationQueryInput").val());
            Dajaxice.async.get_closest_events( 
                (function(data){                                            
                    venuesNames = []
                    venuesDetails = []
                    for (var i = 0; i < data.fVenues.length; i++) {
                        venuesNames.push(data.fVenues[i].name)
                        venuesDetails[ data.fVenues[i].name ] = {
                                                'id' : data.fVenues[i].id,
                                                'lat' : data.fVenues[i].lat,
                                                'lng' : data.fVenues[i].lng,
                                                'address' :data.fVenues[i].address,
                                                'city' :data.fVenues[i].city,
                        }
                    }
                    return venuesNames
                }), 
                {'lat' : new_marker_latlng.lat, 'lng' : new_marker_latlng.lng, 'query' : query }  
            );
        }


    }

}).bind('typeahead:selected', function(obj,datum){
// do stuff upon completion
...
}

1条回答
Lonely孤独者°
2楼-- · 2019-08-24 03:23

Here's a good example of using a json response: How to render JSON response using latest typeahead.js library.

And then to bind the event, you'd combine the above suggestion with something like:

$('.selector').typeahead({
    // base this part on example link given above...
}).bind('typeahead:autocompleted', function (obj, datum) {
    console.log(datum);  // datum will contain the value that was autocompleted
});

Update 1: Regarding the query parameter, your function call is written incorrectly. According to the docs:

replace – A function with the signature replace(url, uriEncodedQuery) that can be used to override the request URL. Expected to return a valid URL. If set, no wildcard substitution will be performed on url.

So you need to pass the URL as the first parameter, and the query string as the second:

remote:{
    replace: function (url, query ) {
    }
}
查看更多
登录 后发表回答