将Javascript变量传递给Python Flas

2024-05-16 18:00:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我读过一些关于通过post/get表单将javascript变量传递给flask的不同示例的帖子。我还是不明白怎么做。根据我的理解,表单创建了一个post/get,然后可以由python flask脚本调用和接收。有人能写一个很简单的例子说明这应该是什么样子吗?

从用javascript中的任何值创建变量开始,然后进行post/get。最后,python上的接收端应该是什么样的,最后从python打印变量。


Tags: 脚本flask表单示例getjavascriptpost帖子
1条回答
网友
1楼 · 发布于 2024-05-16 18:00:50

我是如何使用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,基本上让我们使用Flask的 url_,但使用javascript。查找它,易于安装和使用。否则我想你可以用url替换它,例如'/function\u 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')

我认为要点是在jquery、flask的request.json()和jsonify()函数中查找ajax请求。

相关问题 更多 >