[英]How do you post data from JS to Flask, manipulate the data then send it back to JS?
I'm posting data from my HTML to Flask with: 我将HTML中的数据发布到Flask:
$.ajax({
let name = 'ari_victor'
url: '/send_data',
contentType: "application/json;charset=utf-8",
data: JSON.stringify({name}),
dataType: "json",
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
It arrives on the Backend 它到达后端
@app.route('/send_data', methods=['POST'])
def send_data():
if request.method == 'POST':
data = request.get_json()
name = data['name'].replace('_', ' ').title()
Now how do I send it back? 现在我该怎么发回来? to the HTML/JS?
到HTML / JS?
return name # ?
Edit: I'm doing an ajax post so I dont have to refresh the page, and I'd like to not refresh the page when getting the data back if possible. 编辑:我正在做一个ajax帖子,所以我不必刷新页面,如果可能的话,我不想在恢复数据时刷新页面。 I know how to easily do this with a form and rendering a new template but I'd like to have a go at developing a single page application
我知道如何使用表单轻松完成此操作并呈现新模板,但我想开发一个单页应用程序
Thanks! 谢谢!
In flask view you have to define some kind of response return 'Hello World'
for instance, or preferably json response jsonify(msg=success)
. 在flask视图中,您必须定义某种响应
return 'Hello World'
,或者最好是json response jsonify(msg=success)
。 Then you have to "catch" the response from ajax. 然后你必须“捕获”来自ajax的响应。 It is done here in your ajax statement:
这是在你的ajax语句中完成的:
success: function(response){
console.log(response);
},
response
object contains all response information, just printing here but you can provide callback of your own and do whatever you like :) response
对象包含所有响应信息,只需在此处打印,但您可以提供自己的回调并做任何你喜欢的事情:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.