python - 烧瓶/Python 和 Ajax
问题描述
我发现这看起来非常接近我想要实现的目标。这是我的第一个 Python 项目,我对 Ajax 一无所知,所以我不确定我在看什么:
我得到了 Flask 路线的第一个盒子——我正在这样做,但有很多变量。
我得到了带有 html 的第二个框,它显示了从 Flask 路由传递的变量。
这是我挣扎的最后一个盒子。
在我的模板中,我有:
<div id="insidetemp">
<i class="fas fa-thermometer-half"></i> {{ intTemp }}℃
</div>
<div id="heatingtarget">
<i class="fas fa-fire"></i> {{ targetTemp }}℃ <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 个。
解决方案
一种方法是让您的端点返回一个 JSON 编码的字典,例如:
{
"insidetemp": 37,
"fanspeed": 2800
}
然后在浏览器中使用 JSON 解析:
let data = JSON.parse(msg)
然后根据需要获取值
周围有各种各样的教程可以更好地描述这种事情
推荐阅读
- assembly - 无堆栈函数的跳转/跳转编译策略。(手动使用链接寄存器而不是调用/调用)
- javascript - Moment.js 时区未正确转换
- yii2 - 将网站迁移到新主机并需要更改基本 URL
- amazon-s3 - Terraform 后端配置失败
- ruby-on-rails - 如何将 Ransack 参数传递到路径以在 Rails Rspec 上测试页面
- angular - 角度导航栏问题
- ethereum - 向 Ropsten RPC 错误添加流动性:执行恢复:TransferHelper:TRANSFER_FROM_FAILED
- delphi - 为什么 Delphi 在添加新语言时会为项目的每个配置创建一个单独的 .rc 文件?
- java - 如何使用 Firebase ML Kit 文本识别检测图像中的小数
- python - TensorFlow 动态填充