[英]Send data to Flask backend with Ajax POST request
Ajax requests are all new to me. Ajax 请求对我来说都是新的。 I want to send data from a webpage to my Flask backend using an Ajax request but nothing shows up in the backend:
我想使用 Ajax 请求将数据从网页发送到我的 Flask 后端,但后端没有任何显示:
This is my request:这是我的要求:
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);
}
In the google chrome console the request and the data are showing up correctly, something like:在 google chrome 控制台中,请求和数据正确显示,例如:
<table id="tableID">
<tbody>
<tr>...</tr>
<tr>...</tr>
<tr>...</tr>
</tbody>
</table>
My backend is:我的后端是:
@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)
and nothing shows up in the terminal but:终端中什么也没有显示,但是:
request.method == GET
ImmutableMultiDict([])
(Not a single time in the html page I say "GET" request) Do you have any idea what's wrong with it? (在 html 页面中没有一次我说“GET”请求)你知道它有什么问题吗?
The solution is simple.解决方案很简单。
Depending on which method is used (POST, GET, PUT, ...), data is submitted different根据使用的方法(POST、GET、PUT、...),提交的数据不同
When using POST for example, data is packed as "Form data" and can be accessed by reading request.form
例如使用 POST 时,数据被打包为“表单数据”,可以通过读取
request.form
来访问
When sending a GET request though, data is not submitted as "Form data", but as URL arguments instead, which can be accessed by reading request.args
但是在发送 GET 请求时,数据不是作为“表单数据”提交,而是作为 URL arguments 提交,可以通过读取
request.args
来访问
You can obtain more about request data here in the documentation: https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data您可以在文档中获取有关请求数据的更多信息: https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data
Edit: After reading the question again, I just realised the "POST" in your Code.编辑:再次阅读问题后,我刚刚意识到您的代码中的“POST”。
The request might be interpreted as GET, as the form data is not correctly formatted.该请求可能被解释为 GET,因为表单数据的格式不正确。 The data you are sending must be in a format like
field_name=value,...
您发送的数据必须采用
field_name=value,...
Check this post for an example: https://stackoverflow.com/a/9713078查看此帖子以获取示例: https://stackoverflow.com/a/9713078
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.