繁体   English   中英

使用Ajax提前输入自动完成建议不起作用

[英]typeahead autocomplete suggestion with ajax doesn't work

假设我输入例如“ 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)

我认为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>

有关更多信息,请参见Bloodhound上的Typeahead.js 文档

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

发生了什么变化? 源函数的签名!

现在有2个功能,而不是1个功能。第一个用于同步操作。 第二个用于异步操作。 更改

source: function (query, process) {

source: function (query, dummy, process) {

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

...除外,异步处理器中存在错误。 看到TypeAhead.js和Bloodhound显示了奇数个结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM