简体   繁体   English

提前输入有时返回未定义

[英]Typeahead Sometimes Returns Undefined

I looked at some of the other answers to this problem, but none of them seemed to work for me. 我查看了该问题的其他一些答案,但似乎没有一个对我有用。 I have an input field that uses typeahead. 我有一个使用预输入的输入字段。 It works most of the time, returning the correct values, but sometimes it returns undefined . 它在大多数时间都有效,返回正确的值,但有时返回undefined Here is the .js file: 这是.js文件:

// Add entry item typeahead configuration
$(document).ready(function() {
    var items = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace("add_entry_item_name"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: "items.php?add_entry_item_name=%QUERY"
    });
    items.initialize();
    $("#add_entry_item").typeahead({
        hint: true,
        highlight: true,
        minLength: 2
        }, {
        name: "items",
        displayKey: "item_name",
        source: items.ttAdapter()
    });
});

Here is the items.php file: 这是items.php文件:

// Getting an instance of the connection to the database server
$DB = DB::get_instance();

// Setting the header
header("Content-Type: application/json");

// Exiting if nothing is set
if (!isset($_GET["add_entry_item_name"])) {
    echo json_encode([]);
    exit();
}

// Querying the database and JSON encoding the result
echo json_encode($DB->query("SELECT item_ID, item_name FROM mytable WHERE item_name LIKE ?", array("%{$_GET['add_entry_item_name']}%")));

I have created my own database query function, so that's what you're seeing above. 我已经创建了自己的数据库查询功能,所以这就是您在上面看到的内容。 It works very well, so I'm 99% sure the problem lies elsewhere... 它运作良好,因此我99%肯定问题出在其他地方...

Here's a sample output (items.php?add_entry_item_name=tec): 这是一个示例输出(items.php?add_entry_item_name = tec):

[
    {
        "item_ID": 465,
        "item_name": "Tectonic energy"
    }
]

However, typing in "tec" to my input field returns two undefined s. 但是,在我的输入字段中键入“ tec”会返回两个undefined的。

Any suggestions? 有什么建议么?

Bloodhound's datumTokenizer is configured wrong. 猎犬的datumTokenizer配置错误。 It should be something like this 应该是这样的

datumTokenizer: Bloodhound.tokenizers.obj.whitespace("item_name"),

datumTokenizer – A function with the signature (datum) that transforms a datum into an array of string tokens. datumTokenizer –带有签名(数据)的函数,该函数将数据转换为字符串标记数组。

Here is the reference and here is a DEMO 这是参考 ,这是一个演示

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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