简体   繁体   中英

typeahead.js remote returns nothing

I can't seem to get the remote function of typeahead.js working. I'm posting the code to start:

$(document).ready(function() {
    var locations = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: baseUrl + 'restaurants/fetchZIP/%QUERY'
    });

    $('#location').typeahead({
        hint: true,
        highlight: true,
        minLength: 1,
        source: locations.ttAdapter()
    });
    /*$('#location').keyup(function() {
        $.ajax({
            method: 'POST',
            dataType: 'json',
            url: baseUrl + 'restaurants/fetchZIP/',
            data: $('#add_restaurant').serialize(),
            success: function(data) {
                console.log(data);
            }
        });
    });*/
});

This is the file, where I do the Bloodhound remote thing and I use typeahead on the desired input field. The commented section was a test, to make sure if my DB statement wasn't faulty. I had to rewrite the following code a bit to make the test, but it's basically just a switch from GET to POST:

public function fetchZIP($query)
{
    $cantons = DataLoc::find(array('zip LIKE' => '%'.$query));
    echo json_encode($cantons);
}

This is the action for the 'restaurants/fetchZIP/' page (it's written in CodeIgniter). So, I don't really know what's happening, since I cannot console.log() within the typeahead() function, so I hope anyone can lead me back to the right way.

Firstly, you have to use initialize bloodhound by locations.initialize() right after defining it.

This is how a typeahead is initialized

typeahead(options, [*datasets])

You included source(or datasets) into the options so try something like this

$('#location').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},{
    source: locations.ttAdapter()
});

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM