如何从javascript发送到flask的post请求中获取返回值

如何从javascript发送到flask的post请求中获取返回值,javascript,python,flask,post,Javascript,Python,Flask,Post,新来的。我需要将一个整数变量从html/javascript传递到python flask,以便执行计算并将结果值返回到javascript,这样我就可以在DOM上显示它,而无需刷新页面。下面是我正在处理的HTML结构 <form action="/buy" method="post" id="buy-form"> <h4>Price</h4> <input typ

新来的。我需要将一个整数变量从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>

价格
量
马克斯
我想将输入到
限价
文本输入中的值传递到flask中(使用Javascript)单击“最大化购买”按钮,在python flask中执行计算,然后将结果返回Javascript,这样我就可以在页面上显示它而无需刷新。

您需要的是AJAX:

您可以使用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

好的,你能分享一下flaskpython代码,它会将这个值返回给JS吗?添加了简短的python