将Javascript变量传递给Python Flask
问题描述:
我已阅读了不同示例中的几个帖子,通过post/get窗体将javascript变量传递给flask。我仍然不明白如何做到这一点。根据我的理解,表单会创建一个post/get,然后可以由python flask脚本调用并接收。有人可以写一个非常简单的例子,看看这应该是什么样子?将Javascript变量传递给Python Flask
从javascript中创建一个具有任何值的变量开始,然后进行post/get。最后,python的接收端应该是什么样子,并最终从python打印变量。
答
我如何做到这一点是使用javascript的ajax请求,看起来像这样。我认为最简单的方法也是使用JQuery,因为它可能会更纯粹的JavaScript。
// some movie data
var movies = {
'title': movie_title,
'release_date': movie_release_date
}
$.ajax({
url: Flask.url_for('my_function'),
type: 'POST',
data: JSON.stringify(movies), // converts js value to JSON string
})
.done(function(result){ // on success get the return object from server
console.log(result) // do whatever with it. In this case see it in console
}
Flask.url需要JSGlue这基本上让你用瓶的 url_for但JavaScript的。查看它,轻松安装和使用。否则,我认为你可以只用URL如“/ function_url”
取代它,然后在服务器端,你可能有这样的事情:
from flask import request, jsonify, render_template
import sys
@app.route("/function_route", methods=["GET", "POST"])
def my_function():
if request.method == "POST":
data = {} // empty dict to store data
data['title'] = request.json['title']
data['release_date'] = request.json['movie_release_date']
// do whatever you want with the data here e.g look up in database or something
// if you want to print to console
print(data, file=sys.stderr)
// then return something back to frontend on success
// this returns back received data and you should see it in browser console
// because of the console.log() in the script.
return jsonify(data)
else:
return render_template('the_page_i_was_on.html')
我认为主要的点查找Ajax请求在jquery中,flask的request.json()和jsonify()函数。
这个问题太广泛了。学习如何创建一个最小化的Flask应用程序(这里有很棒的指南:http://flask.pocoo.org/docs/0.12/quickstart/),然后学习如何将参数传递给Flask端点。 – Brennan