我试图创建一个简单的webapp,它使用python中的Flask框架显示表的内容(python中的列表)和更新的标题。烧瓶和html代码如下。
即使单击搜索按钮后页面仍保持不变,标题未更新,我无法在返回的模板中找到表变量。我花了很多时间在这上面但却无法弄清楚这个问题。
# import the Flask class from the flask module
from flask import Flask, render_template, request
# create the application object
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home():
return render_template('index.html')
@app.route('/search', methods=['POST'])
def search():
if request.method == "POST":
print request.json
searchterm = request.json['searchterm']
maxPages = request.json['maxPages']
table = [['Item1', 'http://ecx.images-amazon.com/images/I/51SvVEAaIuL._AA160_.jpg', 21.95, 21.99, 24.06, 9.98, 1.19]]
errors = {}
return render_template('index.html', table = table, title = 'hello')
if __name__ == '__main__':
app.run(debug=True)
HTML
<!DOCTYPE html>
<html>
<head>
{% if title %}
<title>{{title}}</title>
{% else %}
<title>Search</title>
{% endif %}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form class="form-wrapper cf">
{% if searchterm %}
<input type="text" placeholder={{searchterm}} name="searchterm" id="searchterm" >
{% else %}
<input type="text" placeholder="Search..." name="searchterm" id="searchterm" value="">
{% endif %}
<button type="submit" id="btn_submit">Search</button>
</form>
</div>
<div class="row">
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-5">
<form role="form">
<div class="form-group">
<div class="row">s
<div class="col-md-6">
<label for="number">Max Pages:</label>
<input type="number" class="form-control input-sm" name="maxPages" id="maxPages" min="1" value = "1">
</div>
</div>
</div>
</form>
</div>
<div class="col-md-4"> </div>
</div>
</div>
<table>
{% for t in table %}
<tr>
{% for i in t %}
<td>{{ i }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<div id='check'></div>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$('#btn_submit').click( function() {
var data = {}; // data
data['searchterm'] = $('#searchterm').val();
data['maxPages'] = $('#maxPages').val();
$.ajax({
type : "POST",
url : "/search",
data: JSON.stringify(data),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
$('#check').val('result');
}
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
您正在通过AJAX提交表单。所以页面永远不会刷新。您必须根据AJAX响应操作DOM。
或者用以下
替换你的js代码$('#btn_submit').click( function() {
$(this).parent().submit()
});
因此Flask控制器
searchterm = request.form['searchterm']
maxPages = request.form['maxPages']