Typeahead Bootstrap:ajax调用没有下拉列表?

时间:2016-04-21 02:42:26

标签: jquery json ajax twitter-bootstrap-3 typeahead.js

我使用Bootstrap 3和兼容的Typeahead(https://github.com/bassjobsen/Bootstrap-3-Typeahead)。

该网站在Django上运行,我的查询从本地Postgres服务器返回信息。

当我尝试使用AJAX检索来源时,下拉列表不会出现 console.log(data.suggestions)打印一个字符串数组,因此AJAX调用本身似乎正在工作。我在使用process()函数做错了吗?

我的查询以{"suggestions" : ["str1", "str2", "str3"] }格式返回JSON文件,因此我使用data.suggestions来访问包含我的自动填充候选项的数组。

$('.typeahead').typeahead({
    source: function (query, process) {
        return $.getJSON(
            '/path/to/query/',
            { query: query },
            function (data) {
                console.log(data.suggestions);
                return process(data.suggestions);
            });
    }
});

但是,当我传入静态列表作为源时,下拉菜单显示并且自动完成工作正常,因此问题似乎特定于AJAX调用。

var list = ['apple', 'amazon', 'astronaut', 'amigo']
$('.typeahead').typeahead({
  source:list
});

以下是我的HTML文件与Django模板文件的相关部分:

{% load staticfiles %}
<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
  </head>
  <body>
    <div class="container">
      <div class="starter-template">
        <form class="form-inline">
          <div class="form-group" id="results">
            <input type="text" class="form-control input-lg typeahead" name="query" id="kanji" data-provide="typeahead" placeholder="Enter..." autofocus="true" autocomplete="off">
          </div>
        </form>
      </div>
    </div><!-- /.container -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="{% static 'js/bootstrap3-typeahead.min.js' %}"></script>
    <script src="{% static 'js/script.js' %}"></script>
  </body>
</html>

编辑:
我尝试了this question的一些解决方案。但是,同样的事情仍然发生:结果打印到javascript控制台,但仍然没有在实际的HTML页面上生成建议的下拉列表。

EDIT2: 巴斯·约翰森的榜样本身就很完美,这让我自己的情况更加令人费解。

在我的示例中,我在输入框中键入语音单词,查询返回可能的汉字(中文字符)候选列表。 打字&#34;あ&#34;应该返回一个列表,如&#34;亜&#34;,&#34;相&#34;,&#34;爱&#34; ...

我添加了minLength: 0,现在当我将输入字段留空时,整个数据库都会显示为下拉列表。但是当我开始输入时,下拉列表就会消失。所以查询工作正常,Typeahead会识别数组,但只有当我没有输入时?

Query returns results.

The entire database comes up as a dropdown with no input.

2 个答案:

答案 0 :(得分:1)

当我测试你的代码时,我没有发现问题:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <h1>Hello, world!</h1>
    <div class="container">
    <input type="text" class="typeahead">
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    <script src="Bootstrap-3-Typeahead/bootstrap3-typeahead.min.js"></script>
    <script>
    $('.typeahead').typeahead({
        source: function (query, process) {
            return $.getJSON(
                'test.json',
                { query: query },
                function (data) {
                    console.log(data.suggestions);
                    return process(data.suggestions);
                });
        }
    });    
    </script>

  </body>
</html>

使用test.json:

{"suggestions" : ["str1", "str2", "str3"] }

现在正在搜索&#34; str&#34;给出了预期的结果:

enter image description here

使用Bootstrap v 3.3.6进行测试

答案 1 :(得分:0)

事实证明我使用的是Typeahead错误 - 我必须使用Bloodhound来处理远程数据源,尤其是动态查询。

我在Ben Smith使用了这个例子:

How do we set remote in Typeahead.js?

// Instantiate the Bloodhound suggestion engine
var kanji = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/api/get_kanji/?query=%QUERY',
        filter: function (data) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(data.suggestions, function (kanji) {
                return {
                    value: kanji
                };
            });
        }
    }
});

// Initialize the Bloodhound suggestion engine
kanji.initialize();

// Instantiate the Typeahead UI
$('.typeahead').typeahead(null, {
    displayKey: 'value',
    source: kanji.ttAdapter()
});

现在一切正常,在添加必要的脚本和Bass Jobsen Typeahead.js and Bootstrap 3 CSS的其他CSS后,为下拉菜单设置样式。

相关问题