使用ajax的typeahead自动完成建议不起作用

时间:2015-06-19 16:16:56

标签: jquery python ajax flask typeahead.js

让我说我输入例如" j"我应该看到自动完成,比如约翰,在输入标签下面有更多建议,但我不知道。在我的控制台中,我得到["John", "Jane"],没有错误。

的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)

2 个答案:

答案 0 :(得分:1)

我认为Typeahead已更新,现在您的代码无效。

试试这个:

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

有关详细信息,请参阅Typeahead.js docs on Bloodhound

答案 1 :(得分:0)

实际上,你的代码可以正常工作......如果你知道改变了什么。

改变了什么?源函数的签名!

而不是1个过程函数,现在有2.第一个用于同步操作。第二个是异步操作。 变化

source: function (query, process) {

source: function (query, dummy, process) {

并且原帖中的代码应该可以正常工作......

...除外,异步处理器中存在错误。见TypeAhead.js and Bloodhound showing an odd number of results

相关问题