typeahead.js 远程 returns 没有

typeahead.js remote returns nothing

我似乎无法使用 typeahead.js 的远程功能。我正在发布代码以开始:

$(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);
            }
        });
    });*/
});

这是文件,我在其中执行 Bloodhound 远程操作,并在所需的输入字段上使用 typeahead。评论部分是一个测试,以确保我的数据库语句没有错误。我不得不稍微重写以下代码以进行测试,但它基本上只是从 GET 到 POST:

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

这是 'restaurants/fetchZIP/' 页面的操作(它是用 CodeIgniter 编写的)。所以,我真的不知道发生了什么,因为我不能在 typeahead() 函数中 console.log() ,所以我希望任何人都能引导我回到正确的方式。

首先,你必须在定义后立即使用 locations.initialize() 初始化 bloodhound。

这就是 typeahead 的初始化方式

typeahead(options, [*datasets])

您在选项中包含了源(或数据集),所以尝试这样的操作

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

希望对您有所帮助。