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参数提交,可以通过读取request.args
进行访问
您可以在文档中获得有关请求数据的更多信息:https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data
编辑:再次阅读问题后,我刚刚意识到您代码中的“ POST”。该请求可能被解释为GET,因为表单数据的格式不正确。您发送的数据必须采用类似field_name=value,...
的格式查看此帖子以获取示例:https://stackoverflow.com/a/9713078