2015-06-19 68 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