【问题标题】:Trouble in auto-complete using Typeahead使用 Typeahead 自动完成时出现问题
【发布时间】:2015-11-15 19:14:25
【问题描述】:

我遵循了有关如何使用 Typeahead.js 自动完成表单的 youtube 教程。但它似乎没有用。我错过了什么吗?或依赖项的一些变化?这是我现在尝试过的。

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample</title>
</head>
<body>
<form action='main.php' method="get" autocomplete="off">
  <input type="text" id="users" name="user" placeholder="Subject Name">
    <input type="submit" value="Go">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js" />
<script src="js/typeahead.js" />
<script src="js/search.js" />
</body>
</html>

JS
search.js

$(document).ready(function() {
    var users = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'result.php?query=%QUERY',
            wildcard: '%QUERY'
        }
    });

    users.initialize();

    alert(users);

    $('#prefetch .typeahead').typeahead({
        hint:true,
        highlight: true,
        minLength:1
    }, {
        name: 'user',
        displayKey: 'name',
        source: users.ttAdapter()
    });
});

PHP
result.php

<?php

header('Content-Type: application/json');

if(!isset($_GET['query'])) {
    echo json_encode([]);
    exit();
}

$db = new PDO('mysql:host=127.0.0.1;dbname=test','root','');

$users = $db->prepare("
SELECT code,name from sample where name LIKE :query");

$users->execute([
    'query' => "{$_GET['query']}%"
]);

echo json_encode($users->fetchAll());

?>

SQL 包含名为 sample 的表和两个字段,代码(主题代码)和名称(主题名称)。提前致谢。

【问题讨论】:

  • 它在做什么或不做什么?您是否测试过各个部分,例如,如果您直接调用 php,您会得到正确的结果吗?控制台中有什么东西吗?您是否尝试过添加 console.log 调用来记录事情,这样您就可以知道自己走了多远?
  • 对不起,我没有添加这些细节。我在直接调用 PHP 查询 PHP 时得到了正确的结果。即 result.php?query=A 生成所有以 A 开头的课程。但在 HTML 上,我没有生成任何自动完成结果。
  • 抱歉,问题中存在编辑问题。我碰巧通过下载 typeahead.bundle.js 和最新的 jQuery 插件解决了这个问题。毕竟可能存在一些依赖性问题。

标签: javascript php html typeahead.js


【解决方案1】:

只是猜测,但我注意到:

$('#prefetch .typeahead').typeahead({

您在带有id prefetch 的元素中指定了带有class typeahead 的元素,但您没有任何带有classid 的元素。也许(未经测试):

<form action="main.php" method="get" autocomplete="off" id="prefetch">
  <input type="text" id="users" name="user" placeholder="Subject Name" class="typeahead">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多