javascript - 如何从从 javascript 发送到烧瓶的发布请求中获取返回值
问题描述
这里是烧瓶的新手。我需要将一个整数变量从 html/javascript 传递给 python flask,以便执行计算并将结果值返回给 javascript,这样我就可以在 DOM 上显示它而无需刷新页面。下面是我正在处理的 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>
我想通过limit-price
单击按钮将输入到文本输入中的值传递给烧瓶(使用 Javascript),maximize-buy
以便在 python 烧瓶中执行计算,然后将该结果返回给 Javascript,以便我可以将其显示在页面不刷新。
解决方案
你想要的是 AJAX:https ://www.w3schools.com/xml/ajax_intro.asp
您可以使用 XMLHttpRequest:https ://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
这方面的一个例子是:
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 代码大致如下:
@app.route("/do_cool_calculation_stuff",methods=["POST"])
def calculationStuff():
price = request.values["price"]
...
return calculation
推荐阅读
- reactjs - React-Native expo 调试错误未显示任何有用信息或错误消息
- go - 使用通道退出永远循环 - Go Playground 的问题
- pandas - datetime 对象之间的差异仅返回天数
- javascript - 添加任何类型不绑定后的打字稿
- javascript - 引导程序中的统一垂直拉伸单列内容
- c++ - 在 Vector 类对象上调用 push_back() 方法时收到错误
- cassandra - 在 Cassandra 中增加 row_cache_size_in_mb 有什么副作用吗?
- css - CSS 网格库和锚标签
- google-apps-script - 将 Telegram Bot 消息保存到谷歌电子表格中
- android - Android - 谷歌地图聚类错误,标记未重新聚类