【问题标题】:Flask/Python and Ajax烧瓶/Python 和 Ajax
【发布时间】:2018-11-20 21:53:49
【问题描述】:

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

Execute python script -- Ajax and 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 个。

【问题讨论】:

    标签: python ajax templates flask


    【解决方案1】:

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

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

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

    let data = JSON.parse(msg)
    

    然后根据需要获取值

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

    【讨论】:

    • 好的,谢谢。我想你已经回答了这个问题。如果我是对的,那么您要说的是 (msg) 位将保存响应,该响应可能是一个变量或许多变量或我选择的任何其他变量;但重要的是 (msg) 位。
    • msg 是从服务器返回的“东西”……您现有的代码将其视为一个 html 位,将其切换为 JSON 对象可以让您在响应中添加更多内容除了帮助分离关注点——服务器只生成一个漂亮的正式 JSON 对象,Web 客户端担心将它放在正确的位置
    猜你喜欢
    • 2018-05-24
    • 2020-09-18
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多