我正在编写一个简单的Flask应用程序,我想在其中将一些数据从前端发送到Flask应用程序,让它执行一些操作,然后将新数据返回到前端进行显示。我之前已经做过类似的应用程序,并且通过返回POST响应对象而不是render_template()
,我可以简单地返回数据并在前端执行我想要的操作。但是,这次我遇到了问题。
我从前端的Jquery发出POST请求。一切似乎都正常,我可以在浏览器控制台中看到返回的数据,但在显示新数据之前页面会重新加载。它会重新加载到http://xxx.x.x.x:5000/?
。
我可以在Flask控制台中看到对/?
的获取请求。我想知道为什么这样做,以及如何停止它。
(我发现这很难研究,因为大多数搜索引擎会默默地忽略查询中的任何问号。)
Flask应用程序:
import json
from flask import Flask, Response, render_template, request
from src.simple_lookup import analogy_lookup
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route('/')
def hello_world():
return render_template('index.html', results=['a', 'b'])
@app.route('/get_words_simple', methods=['POST'])
def get_words_simple():
print('request.form:', request.form.keys)
data = analogy_lookup(request.form['keyword'], request.form['base'], request.form['goal'])
resp = Response(json.dumps(data), status=200, mimetype='application/json')
print('data:', data)
print('resp:', resp)
return resp
if __name__ == "__main__":
app.run()
jQuery:
$.post('get_words_simple?', data, function(json, status) {
console.log('response:', json);
if (json.hasOwnProperty('error')) {
$('.results').append('<p>' + json.error);
return;
}
var words = json.words;
$.each(words, function(i, text) {
var p = $("<p>");
p.append(text);
$('.results').append(p);
});
});
烧瓶控制台:
127.0.0.1 - - [27/Dec/2018 11:12:21] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2018 11:12:21] "GET /static/js/main.js HTTP/1.1" 200 -
request.form: <bound method MultiDict.keys of ImmutableMultiDict([('keyword', ''), ('base', ''), ('goal', '')])>
127.0.0.1 - - [27/Dec/2018 11:12:23] "GET /? HTTP/1.1" 200 -
127.0.0.1 - - [27/Dec/2018 11:12:23] "GET /static/js/main.js HTTP/1.1" 200 -
data: ['obtuvo', 'takata', 'stadshypotek', 'kriwet', 'shafiee', 'martorell', 'collum', '29,400', 'muteesa', 'patzek']
resp: <Response 111 bytes [200 OK]>
127.0.0.1 - - [27/Dec/2018 11:12:23] "POST /get_words_simple? HTTP/1.1" 200 -
答案 0 :(得分:0)
问题在于,如果Bootstrap在表单组中,它会覆盖type="submit"
按钮的功能。因此我的Jquery所做的一切都正确,但是按钮html的内容却搞砸了一切,并尝试以不同的方式发出发布请求