繁体   English   中英

使用 Ajax POST 请求将数据发送到 Flask 后端

[英]Send data to Flask backend with Ajax POST request

Ajax 请求对我来说都是新的。 我想使用 Ajax 请求将数据从网页发送到我的 Flask 后端,但后端没有任何显示:

这是我的要求:

  function confirm() {
    const xhttp = new XMLHttpRequest();
    const data = document.getElementById("tableID");
    xhttp.open("POST", "app.py");
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(data);
    console.log(xhttp);
    console.log(data);
  }

在 google chrome 控制台中,请求和数据正确显示,例如:

<table id="tableID">
    <tbody>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
    </tbody>
</table>

我的后端是:

@app.route('/admintools', methods=["POST", "GET"])
def admintools():
    tracks = observed_tracks(get_tracks())
    if request.method == "POST":
        print("request.method == POST")
        print(request.form)
    if request.method == "GET":
        print("request.method == GET")
        print(request.form)
    return render_template("tools/admintools.html", tracks=tracks)

终端中什么也没有显示,但是:

request.method == GET
ImmutableMultiDict([])

(在 html 页面中没有一次我说“GET”请求)你知道它有什么问题吗?

解决方案很简单。

根据使用的方法(POST、GET、PUT、...),提交的数据不同
例如使用 POST 时,数据被打包为“表单数据”,可以通过读取request.form来访问

但是在发送 GET 请求时,数据不是作为“表单数据”提交,而是作为 URL arguments 提交,可以通过读取request.args来访问

您可以在文档中获取有关请求数据的更多信息: https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data

编辑:再次阅读问题后,我刚刚意识到您的代码中的“POST”。
该请求可能被解释为 GET,因为表单数据的格式不正确。 您发送的数据必须采用field_name=value,...
查看此帖子以获取示例: https://stackoverflow.com/a/9713078

暂无
暂无

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

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