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

时间:2020-05-26 06:55:14

标签: javascript ajax forms flask ajaxform

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”请求) 你知道这是怎么回事吗?

1 个答案:

答案 0 :(得分:0)

解决方案很简单。

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

进行访问

尽管在发送GET请求时,数据不是作为“表单数据”提交,而是作为URL参数提交,可以通过读取request.args

进行访问

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

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

相关问题