Javascript js到烧瓶,然后在单页应用程序中返回到js
对于我的单页web应用程序,我需要:Javascript js到烧瓶,然后在单页应用程序中返回到js,javascript,python,json,ajax,flask,Javascript,Python,Json,Ajax,Flask,对于我的单页web应用程序,我需要: 将json从.js发送到flask(完成) 通过python函数-getString()运行输入,并获得str输出(完成) 将str输出发送回.js文件(问题) 以下是flask应用程序: @app.route('/',methods =['GET','POST']) def index(): req = json.dumps(request.get_json()) if request.method == 'POST':
@app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
问题是没有发送jsonify(结果),这可能是由于调用jsonify时request.method==“POST”切换到else。有没有办法修复我的代码,将str输出发送到.js
下面是.js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
我想你误解了GET和POST是什么,GET是一个请求,它只从后端获取内容,没有消息正文,但是POST可以发送正文并接收内容 请尝试以下方法:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})