简体   繁体   English

如何将 JavaScript 变量传递给 Flask?

[英]How to pass JavaScript variable to Flask?

I want to access the JavaScript variable file in the app.py file but it's giving me a bad request which says "Did not attempt to load JSON data because the request Content-Type was not 'application/json'".我想访问app.py文件中的 JavaScript 变量文件,但它给了我一个错误的请求,上面写着“没有尝试加载 JSON 数据,因为请求 Content-Type 不是 'application/json'”。

Since I intend to pass only one variable to the Python file, is there not some other shorter method to do so other than using JSON?由于我打算只将一个变量传递给 Python 文件,除了使用 JSON 之外,没有其他更短的方法吗?

@app.route("/", methods=["GET", "POST"])
def index():
    if "stop" in request.form:
        data = {}
        data["file"] = request.json("file")
        print(data, file=sys.stderr)
    return render_template("index.html")
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="./static/styles/style.css">
    <title>Title</title>
</head>
<body>
<form method="post">
    <input type="submit" name="start" onclick="startRec" value="start"/>
    <input type="submit" name="stop" value="stop"/>
</form>
<script>
        const startRec = () => {
            var file = {"file" : "whatever"};
            $.ajax({
            url : "/",
            type : "POST",
            contentType : "application/json",
            data : JSON.stringify(file)
            })
            .done(function(res){
            console.log(res)
            });
    }
</script>
</body>
</html>

You submit the form and also do your ajax call at same time.您提交表单并同时进行 ajax 调用。

Use a Form or an Ajax function to send data.使用表单或 Ajax 函数发送数据。 And not both.而不是两者兼而有之。

Remove your form, use normal buttons with onclick mapped to your ajax function.删除您的表单,使用映射到您的 ajax 函数的 onclick 的普通按钮。

Terminology tips:术语提示:

  • Think less in terms of "files" and more in terms of "applications".少考虑“文件”,多考虑“应用程序”。 Your code is stored as text in a file, but when the Python or JS runtime executes the code, it runs as an application in memory, not on disk (where files live).您的代码作为文本存储在文件中,但是当 Python 或 JS 运行时执行代码时,它作为应用程序在内存中运行,而不是在磁盘(文件所在的位置)上。
  • The client and the server don't share variables.客户端和服务器不共享变量。 In our case, they share raw data via HTTP requests.在我们的例子中,它们通过 HTTP 请求共享原始数据。 A client serializes data (possibly stored in variables) into a raw byte sequence, creates a request with a payload and sends it over the network.客户端将数据(可能存储在变量中)序列化为原始字节序列,创建带有有效负载的请求并通过网络发送。 The server deserializes the data and creates variable(s) to store the values in the memory reserved for its process.服务器反序列化数据并创建变量以将值存储在为其进程保留的内存中。 After processing the data, the server sends a response, which can also have a data payload.处理完数据后,服务器会发送一个响应,其中也可以有一个数据负载。

This may seem overly pedantic, but having a clear mental picture of the client-server architecture is important to be able to ask the right questions and implement features easily.这可能看起来过于迂腐,但对客户端-服务器架构有一个清晰的心理图景对于能够提出正确的问题并轻松实现功能非常重要。


Now, there are multiple ways to send data.现在,有多种方法可以发送数据。 You can use JSON or form data to format a POST payload, but it looks like you're conflating the two.您可以使用 JSON 或表单数据来格式化 POST 有效负载,但看起来您将两者混为一谈。

if "stop" in request.form: deals with the form, but data["file"] = request.json("file") deals with JSON. if "stop" in request.form:处理表单,但data["file"] = request.json("file")处理 JSON。 When the form is submitted, it POSTs the form data to the route / , and "stop" is indeed in request.form .提交表单时,它会将表单数据 POST 到路由/ ,并且"stop"确实在request.form中。 But the request type isn't JSON, it's form data, hence the error once you attempt to access request.json .但是请求类型不是 JSON,它是表单数据,因此一旦您尝试访问request.json就会出错。

You have two options:你有两个选择:

  1. Use form data triggered by the HTML.使用由 HTML 触发的表单数据。 Put whatever you want the payload to be entirely within the form.将您希望有效负载完全放在表单中的任何内容。 No JS will be involved.不会涉及任何 JS。 Here's an example .这是一个例子
  2. Use an asynchronous JS request.使用异步 JS 请求。 Remove the form method="post" , attach an event listener to the form submission, call event.preventDefault() inside the handler, then use jQuery to post the data.删除表单method="post" ,将事件监听器附加到表单提交,在处理程序中调用event.preventDefault() ,然后使用 jQuery 发布数据。 Here's an example .这是一个例子

Either way, either approach is about as short as it gets.无论哪种方式,任何一种方法都尽可能短。 Libraries like htmx exist that create an illusion of simplicity, but there's a learning curve and potential for further misunderstandings when failures arise, so I'd stick to the basics for now--you can get surprisingly far with them.存在像htmx这样的库会产生简单的错觉,但是当出现故障时,存在学习曲线和进一步误解的可能性,所以我现在坚持基础知识——你可以用它们走得更远。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM