将 Javascript 变量传递给 Python Flask [英] Passing Javascript Variable to Python Flask
问题描述
我已经阅读了几个关于不同示例的帖子,这些示例通过 post/get 表单将 javascript 变量传递给flask.我仍然不明白如何做到这一点.根据我的理解,该表单创建了一个 post/get,然后可以被 python flask 脚本调用和接收.有人可以写一个非常简单的例子来说明这应该是什么样子吗?
I have read several postings on different examples for passing a javascript variable to flask through post/get forms. I still don't understand how to do this. From my understanding, the form creates a post/get that can then be called and received by the python flask script. Can someone write up a very simple example on what this should look like?
从在 javascript 中创建一个具有任何值的变量开始,然后进行 post/get.最后python上的接收端应该是什么样子,最后从python打印变量.
Starting from creating a variable with any value in javascript and then making the post/get. Lastly what should the receiving end on python should look like and finally print the variable from python.
推荐答案
我如何做到这一点是使用来自 javascript 的 ajax 请求,它看起来像这样.我认为最简单的方法是使用 JQuery,因为使用纯 JavaScript 可能会更冗长.
How I did this was using an ajax request from the javascript which would look something like this. I think the easiest way would be using JQuery as well since it might be a bit more verbose with pure 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 基本上让你使用 Flask 的url_for 但使用 javascript.查找一下,安装使用方便.否则我认为你可以用 url 替换它,例如 '/function_url'
Flask.url requires JSGlue which basically let's you use Flask's url_for but with javascript. Look it up, easy install and usage. Otherwise I think you could just replace it with the url e.g '/function_url'
然后在服务器端你可能有这样的事情:
Then on the server side you might have something like this:
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')
我觉得主要是在jquery中查找ajax请求,flask的request.json()和jsonify()函数.
I think the main points are to look up ajax requests in jquery, flask's request.json() and jsonify() functions.
更正语法
这篇关于将 Javascript 变量传递给 Python Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!