简体   繁体   中英

Typeahead Bootstrap: No dropdown shows for ajax calls?

I'm using Bootstrap 3 with the compatible Typeahead ( https://github.com/bassjobsen/Bootstrap-3-Typeahead ).

The site runs on Django, and my query returns info from a local Postgres server.

When I try to use AJAX to retrieve the source, the dropdown doesn't appear.
console.log(data.suggestions) prints an array of strings, so the AJAX call itself seems to be working. Am I doing something wrong with the process() function?

My query returns a JSON file, in the format {"suggestions" : ["str1", "str2", "str3"] } , so I use data.suggestions to access the array containing my autocomplete candidates.

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

However, when I pass in a static list as the source, the dropdown menu shows up and autocomplete works fine, so the problem seems to be specific to the AJAX call.

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

Here are the relevant parts of my html file with Django template files:

{% 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>

EDIT:
I tried some of the solutions to this question . However, the same thing still happens: the results print to the javascript console, but still doesn't generate a dropdown list of suggestions on the actual HTML page.

EDIT2: Bass Jobsen's example works perfectly on its own, which makes my own situation all the more puzzling.

In my example, I type phonetic words into the input box, and the query returns a list of possible kanji (chinese character) candidates. Typing "あ" should return a list like "亜", "相", "愛"...

I added minLength: 0 , and now when I leave the input field blank, the entire database comes up as a dropdown. But when I start typing, the dropdown disappears. So the query's working, the array is being recognized by Typeahead, but only when I have no input??

查询返回结果。

整个数据库显示为没有输入的下拉列表。

when i test your code, i do not find an issue:

<!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>

With test.json:

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

Now searching for "str" gives the expected result:

在此输入图像描述

Tested with Bootstrap v 3.3.6

It turns out I was using Typeahead wrong - I have to use Bloodhound to work with a remote data source, especially for dynamic querying.

I used this example by 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()
});

Now everything works perfectly, after adding the necessary scripts and some additional CSS from Bass Jobsen 's Typeahead.js and Bootstrap 3 CSS to style the dropdown menu.

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