简体   繁体   中英

typeahead autocomplete suggestion with ajax doesn't work

let's say I type for example "j" and I should see autocomplete like for example John with more suggestions below input tag, but I don't. In my console I get ["John", "Jane"] , no errors.

test.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
</head>
<body>
<div id="aa">
  <input class="typeahead" type="text" placeholder="names">
</div>

<script src="../static/jquery-1.11.3.min.js"></script>
<script src="../static/typeahead.bundle.js"></script>
<script>
 $('#aa .typeahead').typeahead(null, {
        source: function (query, process) {
        $.ajax({
          url: '/test/',
          type: 'GET',
          contentType: "application/json; charset=utf-8",
          data: {'query': query},
          success: function(data) {
            console.log(data.options);
            process(data.options);
          }
        });
      }
   });
 </script>
 </body>
 </html>

app.py

from flask import Flask, render_template, url_for, jsonify, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('test.html')

@app.route('/test/')
def test():
    print request.args.get('query')
    return jsonify(options=["John","Jane"])
if __name__ == '__main__':
    app.run(debug = True)

I think Typeahead has been updated, and now your code won't work.

Try this:

<html lang="en">
<head>
    <meta charset="utf-8"/>
</head>
<body>
<div id="aa">
  <input class="typeahead" type="text" placeholder="names">
</div>

<script src="../static/jquery-1.11.3.min.js"></script>
<script src="../static/typeahead.bundle.js"></script>
<script>
  var engine = new Bloodhound({
    remote: {
      url: '/test/?query=*',
      wildcard: '*',
      transform: function (response) {
        return response.options;
      }
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    datumTokenizer: Bloodhound.tokenizers.whitespace,
  });

$('#aa .typeahead').typeahead(null, {
  name: 'my-dataset',
  source: engine
});
</script>
</body>
</html>

For more information, see the Typeahead.js docs on Bloodhound .

Actually, your code can work fine...if you know what changed.

What changed? The signature of the source function!

Instead of 1 process function, there are now 2. The first is for synchronous operation. The second is for asynchronous operation. Change

source: function (query, process) {

to

source: function (query, dummy, process) {

and the code in the original post should work fine...

...except, there is a bug in the async processor. See TypeAhead.js and Bloodhound showing an odd number of results

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