首页 > 解决方案 > 如何从从 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,以便我可以将其显示在页面不刷新。

标签: javascriptpythonflaskpost

解决方案


你想要的是 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

推荐阅读