您如何通过POST传递Javascript变量以在Flask中使用?

问题描述 投票:0回答:1

因此,我有一个按下按钮后创建的JS变量,我需要将其传递给我的应用程序以在flask中进行处理。我目前正在尝试使用查询字符串来完成此操作,但我不确定自己在做什么。

在html中,我设置了这样的表单:

<form action="/deleteBook" method="POST" onsubmit="deleteBook()">
                <input type="submit" value="Delete" />
 </form>

调用此函数以应用查询字符串:

function deleteBook() {
        var existingUrl = window.location.href;
        window.location.href = existingUrl + '?itemID=' + itemToRemove;
    };

然后我想通过烧瓶处理该变量:

@app.route('/deleteBook', methods=["POST"])
def deleteBook():

if(request.method == "POST"):

    itemID = request.args.get('itemID')

在我看来,代码应该检测到表单提交(基本上是单击按钮),调用deleteBook(),然后应该将查询字符串附加到URL上,然后可以在flask中对其进行处理。

我知道我缺乏有关html / js /处理数据的一些基本知识,因此我不太确定从何而来。我应该使用PHP以某种方式处理请求吗?还是我根本不用表格?还是在烧瓶中有一种更简便的方法,无需使用POST即可获取数据?我不确定是否有任何建议,谢谢!

javascript python html flask
1个回答
0
投票

好吧,我为这种独特的问题找到了自己的风格,所以我会尽力解释我对答案的想法。首先,我只需要调用函数的形式其次,我将使用带有“ POST”配置的函数调用“ XMLHttpRequest”HTML

<form onsubmit="deleteBook()">
  <input type="submit" value="Delete " />
</form>

JavaScript

function deleteBook () {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', existingUrl + '?itemID=' + itemToRemove, true); //The second argument is the url you wish to 'POST' to
  xhr.send(); //if you want to do something if your flask returns something, 'xhd.onload = function () {}'
}
© www.soinside.com 2019 - 2024. All rights reserved.