首页 > 解决方案 > 如何通过 POST 传递 Javascript 变量以在 Flask 中使用?

问题描述

所以我有一个在按下按钮后创建的 JS 变量,我需要将它传递给我的应用程序以在烧瓶中处理。我目前正在尝试使用查询字符串来做到这一点,但我不确定我在做什么。

在 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,然后可以在烧瓶中处理。

我知道我缺乏一些关于 html/js/处理数据的基本知识,所以我不确定从这里去哪里。我应该使用 PHP 以某种方式处理请求吗?还是我根本不应该使用表格?或者也许在烧瓶中有一种更简单的方法来获取数据而不使用 POST?我不确定,所以任何建议都值得赞赏,谢谢!

标签: javascriptpythonhtmlflask

解决方案


好吧,对于这样一个独特的问题,我发现你的风格很独特,所以我会尽力解释我对答案的想法。首先,我只会让表单调用函数其次,我会让函数调用带有“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 () {}'
}

推荐阅读