首页 > 解决方案 > 通过 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 的代码示例。

我发现很难理解我在其他地方读到的解释是如何工作的,因为假设语法被理解,如果语法清楚地向我说明,我将不胜感激。

标签: javascriptpythonajaxflaskpost

解决方案


的第二个参数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); 


推荐阅读