のスクリプトでコードが空<div id='empty'>
@app.route('/search', methods=['POST'])
def search():
name = request.form['name'];
j=CARDS_COLLECTION.find({'name':"whatever"})
for k in j:
print k
print name
return json.dumps({'status':'OK','name':name});
@app.route('/page')
def page():
return render_template('page.html')
に結果を示すことが必要ajax関数の中で、成功関数の内部にある。あなたがしなければならないことの例を見てください。フラスコインポートフラスコ、要求、render_templateから
#1 app.py 、
app = Flask(__name__)
@app.route('/search', methods=['POST'])
def search():
# this works and I don't know why because we should use
# request.get_json() to parse json data...
name = request.form['name']
# using the jsonify function to turn dict into json and send
# the correct HTTP header
return jsonify({"status": "OK", "name": name}), 200
@app.route('/')
def hello_world():
return render_template("search.html")
if __name__ == '__main__':
app.run(debug=True)
とHTMLページjsonify:答えを
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="search_field" type="text">
<button>Search!!</button>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function() {
$('button').click(function() {
// we dont use form because we wanna send data with javascript
// so we get the value of input into a variable
var name_field = $("#search_field").val();
// I wanna send the data as json documento, so we create one to put our values
var my_data = {
name: name_field
};
$.ajax({
url: "/search",
data: my_data, // here come the json data
type: 'POST',
success: function(response) {
// I said that you must use parseJSON but I was wrong
// because the data is already a JSON document and try to
// parse it again leads to an error... so, don't use it for now
// more details http://api.jquery.com/jquery.parsejson/
// var data = $.parseJSON(response);
// just to see what is comming from server
console.log(response);
// now we will create a div above every element on body
// notice that I'm escaping the " for id... there are many ways and methods
// to insert html or text, aways depends on your needs.
$('body').prepend("<div id=\"empty\">"+response.name+"</div>");
},
error: function(error) {
console.log(error);
}
});
});
});
</script>
</body>
</html>
おかげで、私は何かを誤解していない限り、あなたのコードをユーザーがフィールドに入力したのと同じテキストをページに挿入しています。/search関数で実行された検索の結果をページに挿入する必要があります。 @xFilipe –
divタグの内部にコードが挿入されているので、div関数自体を挿入するには、append関数などを使用する必要があります。コードの詳細と挿入する場所を表示してください私はあなたのコードを編集するために管理 –
は、検索機能は次のようである:app.route( '/検索'、メソッド= [ 'POST']) @ デフ)(検索: \t TEMP = [] \t名= request.form ['name'];\t j = CARDS_COLLECTION.find({'functionname':{'$ regex':name.lower()}}、{"_ id":1、 "url":1、 "name":1、 'sets': 1 'functionalname':1}) \t名= "" j内のkについて \t: \t \t名=名+ STR(K) \t \t \t戻りjson.dumps({ 'ステータス': 'OK '、' name ':name}); –