2015-06-19 64 views
0

比方说,我键入例如“j”,我应该看到自动完成,如约翰在输入标签下面有更多的建议,但我不知道。在我的控制台我得到["John", "Jane"],没有错误。typeahead自动完成的建议与AJAX不起作用

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

显然,您期待'process'做些什么......它没有这样做......您希望'process'做什么?是lookahead.js api的一部分吗? –

回答

1

我觉得已经事先键入的内容进行了更新,现在您的代码将无法正常工作。

试试这个:

<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

+0

thx为您的答案。这对我的例子[“John”,“Jane”]以及当我输入“j”时的列表工作正常。但是,如果我将这个列表更改为[“John”,“Jane”,“Sandra”,“Xerox”]并键入例如“x”或“o”,那么我总是会得到一个建议John – user729076

+1

Huh。我不完全确定这是为什么发生。 我可以通过稍微修改'test()'函数来修复它,只返回其中包含查询的名称: 'return jsonify(options = [name for name in names if query.lower()in name.lower()])' –

+0

thx您的帮助! – user729076

0

其实,你的代码可以正常工作......如果你知道发生了什么变化。

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

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

source: function (query, process) { 

source: function (query, dummy, process) { 

,并在原来的职位代码应该很好地工作......

...除了,还有在异步处理器中的错误。请参阅TypeAhead.js and Bloodhound showing an odd number of results