[英]How can I get a return value from a post request sent from javascript to flask
New to flask here.这里是 flask 的新手。 I need to pass an integer variable from html/javascript to python flask in order to perform a calculation and return the result value to javascript so that I can display it on the DOM without refreshing the page.
我需要将 integer 变量从 html/javascript 传递到 python flask 以执行计算并将结果值返回到 javascript 以便我可以在 DOM 上显示它而无需刷新页面。 Below is the HTML structure I'm dealing with.
下面是我正在处理的 HTML 结构。
<form action="/buy" method="post" id="buy-form">
<h4>Price</h4>
<input
type="text"
id="limit-price"
name="limit-price"
/>
<h4>Quantity</h4>
<input
type="text"
id="limit-quantity"
name="limit-quantity"
/>
<button type="button" id="maximize-buy">Max</button>
<input type="submit" name="buy" value="BUY" id="submit-buy" />
</form>
I want to pass the value thats typed into the limit-price
text input over into flask (using Javascript) at the click of the maximize-buy
button in order to perform a calculation in python flask and then return that result back to Javascript so that I can display it on the page without refreshing.我想在单击
maximize-buy
按钮时将输入到limit-price
文本中的值传递到 flask(使用 Javascript),以便在 python flask 中执行计算,然后将该结果返回到 Javascript,以便我可以在页面上显示它而无需刷新。
What you want is AJAX: https://www.w3schools.com/xml/ajax_intro.asp你要的是AJAX: https://www.w3schools.com/xml/ajax_intro.asp
You could use an XMLHttpRequest:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest您可以使用 XMLHttpRequest:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
An example of this would be something like:这方面的一个例子是这样的:
let price = document.getElementById("limit-price").innerHTML;
let xhttp = new XMLHttpRequest();
let resp;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resp = this.responseText;
// display_result_here_in_js
}
};
xhttp.open("POST", "/do_cool_calculation_stuff", true);
xhttp.send({"price":price});
Python code would be along the lines of: Python 代码如下:
@app.route("/do_cool_calculation_stuff",methods=["POST"])
def calculationStuff():
price = request.values["price"]
...
return calculation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.