javascript - 如何通过 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?我不确定,所以任何建议都值得赞赏,谢谢!
解决方案
好吧,对于这样一个独特的问题,我发现你的风格很独特,所以我会尽力解释我对答案的想法。首先,我只会让表单调用函数其次,我会让函数调用带有“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 () {}'
}
推荐阅读
- slurm - SLURM“srun module load”命令退出并出现错误
- git-bash - windows git bash中奇怪的命令替换行为
- r - 忽略要应用于数据帧列表 R 的 Ifelse 语句 R 中的 NA
- django - 如何使用 Rest 框架将附件发送到 Django webapp?
- motion - 发生事情时如何启动 MotionLayout 的动画?
- aws-cli - jonhadfield/acli 安装期间出错
- sql - 将一个表中的值插入到另一个表中,其中外键值 = 另一个表中的值
- discord.py - 我如何查看提到的人 | 不和谐.py
- java - “前提条件”和日志记录参数不应该需要评估
- mongodb - mongoimport 导致错误的 ObjectId 格式