首页 > 解决方案 > 烧瓶/Python 和 Ajax

问题描述

我发现这看起来非常接近我想要实现的目标。这是我的第一个 Python 项目,我对 Ajax 一无所知,所以我不确定我在看什么:

执行python脚本——Ajax和Flask

我得到了 Flask 路线的第一个盒子——我正在这样做,但有很多变量。

我得到了带有 html 的第二个框,它显示了从 Flask 路由传递的变量。

这是我挣扎的最后一个盒子。

在我的模板中,我有:

<div id="insidetemp">
    <i class="fas fa-thermometer-half"></i> {{ intTemp }}&#8451;
</div>
<div id="heatingtarget">
    <i class="fas fa-fire"></i> {{ targetTemp }}&#8451; <i class="far fa-clock sm"></i>
</div>

这些都是从我的 / 路线生成的。

他有:

function cputemp2() {
    $.ajax({
        type: "POST",
        url: "/cputemp",
        dataType: "html",
        success: function(msg) {
            console.log(msg);
            $("#swiss").html(msg);
        },
        error: function (xhr, status, error) {
            console.log(error);
        }
    });
}

所以,我想我可以更改函数的名称。我会将 URL 更改为 /。我会将 id 更改为 #insidetemp 以定位模板中的 div。

我将首先尝试一下:

function syncvalues() {
        $.ajax({
            type: "POST",
            url: "/",
            dataType: "html",
            success: function(msg) {
                console.log(msg);
                $("#insidetemp").html(msg);
            },
            error: function (xhr, status, error) {
                console.log(error);
            }
        });
    }

但是我将如何添加更多变量?如果有人可以让我开始使用 2 个变量,那么我希望我可以将其扩展到 10 个。

标签: pythonajaxtemplatesflask

解决方案


一种方法是让您的端点返回一个 JSON 编码的字典,例如:

{
    "insidetemp": 37,
    "fanspeed": 2800
}

然后在浏览器中使用 JSON 解析:

let data = JSON.parse(msg)

然后根据需要获取值

周围有各种各样的教程可以更好地描述这种事情


推荐阅读