javascript - 通过 AJAX 将 Javascript 变量发布到 Python 控制器
问题描述
我是编程新手,现在我的深度不够......
我正在尝试制作一个应用程序,该应用程序使用基于按钮点击的信息,然后可以根据这些按钮点击进行数据分析。这适用于纯 Javascript,但我需要能够将这些数据保存在数据库中,以便我可以在另一个时间登录并从我离开的地方继续,而不是重新开始。
我需要能够通过单击一个按钮将存储在变量中的信息传递到服务器以保存在数据库中,并在单击另一个按钮时将信息从数据库发送回 javascript。
到目前为止,我已经制作了一个 Flask 应用程序,但我正在努力使用 AJAX 将 python 控制器与 javascript 连接起来。
关于这个主题已经有很多问题了,但是在阅读并尝试了我能找到的所有解决方案之后,我仍然在苦苦挣扎。
这是我在这里找到的一种解决方案(使用 XMLHttpRequest 发送 POST 数据),但它给了我一个 400 错误:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/postmethod', true); // '/postmethod' is where I am hoping to deal with this data on the python controller
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(data); //data is a map which contains about 20 key value pairs.
我希望这会将数据记录到控制台上,但它没有这样做。我对“console.log(this.responseText);”的目的可能完全错误。
这是我在 python 方面所能得到的:
@app.route('/postmethod', methods = ['POST'])
def postmethod():
if request.method == "POST":
//I want to execute database commands here using the data passed from the javascript. But I do not know how to get the data as a variable in Python from Javascript.
我真的很感激一个如何使用按钮发布数据的例子。我需要查看 python 控制器和 javascript 的代码示例。
我发现很难理解我在其他地方读到的解释是如何工作的,因为假设语法被理解,如果语法清楚地向我说明,我将不胜感激。
解决方案
的第二个参数xhr.open
是 URL。我认为您需要定义可访问后端的完整 URL。例如
new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/postmethod', true); // '/postmethod' is where I am hoping to deal with this data on the python controller
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send(data);
推荐阅读
- kotlin - Kotlin 检查数据类属性是否全部为空
- javascript - React:尝试自动选择新创建的列表项
- mysql - select in select mysql about subquery
- javascript - 使用Java在jsp页面中插入和更新数据并保存到数据库中
- arrays - 使用 $arr[x] 和 @arr[x] 访问数组的区别
- angular - 如何在 Angular 应用程序中制作更好的 Route 结构?
- jquery - 从 jQuery 调用 Angular 9 函数
- node.js - loopback 4:如何实现多对多关系?
- php - 单页中的多个分页 - yii2 framewrok
- azure-ad-b2c - 自定义策略和内置用户流中的注销行为更改