weixin_33739541 2018-11-20 21:53 采纳率: 0%
浏览 37

Flask / Python和Ajax

I found this which looks very close to what I'm trying to achieve. This is my first Python project and I know nothing about Ajax so I'm not sure what I'm looking at:

Execute python script -- Ajax and Flask

I get the first box with the Flask route - I'm doing that, but with lots of variable.

I get the second box with the html that displays the variable passed from the Flask route.

It's the last box that I'm struggling with.

In my template I have:

<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>

These are all generated from my / route.

He has:

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);
        }
    });
}

So, I guess I can change the name of the function. I'd change the URL to /. I'd change the id to #insidetemp to target the div in my template.

I'm going to take a stab at the first bit:

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);
            }
        });
    }

But how would I add more variables? If someone can get me started with 2 variables then I'm hoping I can extend that to 10.

  • 写回答

1条回答 默认 最新

  • weixin_33739523 2018-11-20 22:15
    关注

    one way would be to have your endpoint return a JSON encoded dictionary, like:

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

    and then parse this in the browser using JSON:

    let data = JSON.parse(msg)
    

    and then get values out as you want

    there are various tutorials around that describe this sort of thing much better

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置