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

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度