2016-09-21 12 views
1

私はデモを準備しています。これは初めて "web dev"をやっています。 それでは、まったく問題ではないかもしれませんが、ここで私がやろうとしていることがあります。検索ボックスをオートコンプリートしてフラスコに値を渡す

入力としてオートコンプリートする2つの検索ボックスが必要です。

First search box: name 
Second search box: song 

は、私は2つのファイルを持っているnames.txtとsongs.txt

だから、アイデアは、ユーザーが名前を入力しているときにユーザがあるとき、オートコンプリートを生成するnames.txtからの読み取りとされていることですタイピングの歌、

そして、これらの値は、バックエンドでのアプリをフラスコに渡されるsongs.txt

に基づいて、検索ボックスのオートコンプリート..私は非常に単純な例のように必要

@app.route('/search', method=['post']) 
def process(): 
    return name, song, and list of other songs with score (list a table) 

(のnothinただ、これを行いグラムの空想)..

おかげ

+0

持っていますか?データを返すためにフラスコAPIを構築するだけで助けが必要ですか? – GMarsh

+0

@GMarsh no ..私もJavascriptの部分が必要です – Fraz

答えて

3

どのようにjQueryの - オートコンプリートの使用に関する。これは、あなたが始める必要があります:あなたは、オートコンプリートボックスが自動的に投稿

**/app.py** 

from flask import Flask, request, render_template, jsonify 
app = Flask(__name__) 

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

@app.route("/search/<string:box>") 
def process(box): 
    query = request.args.get('query') 
    if box == 'names': 
     # do some stuff to open your names text file 
     # do some other stuff to filter 
     # put suggestions in this format... 
     suggestions = [{'value': 'joe','data': 'joe'}, {'value': 'jim','data': 'jim'}] 
    if box == 'songs': 
     # do some stuff to open your songs text file 
     # do some other stuff to filter 
     # put suggestions in this format... 
     suggestions = [{'value': 'song1','data': '123'}, {'value': 'song2','data': '234'}] 
    return jsonify({"suggestions":suggestions}) 

if __name__ == "__main__": 
    app.run(debug=True) 

**/templates/index.html** 

<head> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.26/jquery.autocomplete.min.js"></script> 
</head> 

<body> 
    Names: 
    <input type="text" name="names" id="autocomplete1"/> 

    Songs: 
    <input type="text" name="songs" id="autocomplete2"/> 


    <script> 
    $('#autocomplete1').autocomplete({ 
     serviceUrl: '/search/names', 
     dataType: 'json', 
     onSearchComplete: function (query, suggestions) { 
     console.log(query); 
     } 
    }); 

    $('#autocomplete2').autocomplete({ 
     serviceUrl: '/search/songs', 
     dataType: 'json', 
     onSearchComplete: function (query, suggestions) { 
     console.log(query); 
     } 
    }); 
    </script> 
</body> 
関連する問題