几年前我确实有过这段代码,最近又回来了,我有一个刷新网页数据的javascript。我正在使用json调用服务器,并接收回我认为正确的内容。
我的python数据库代码,它似乎工作得很好。
cur = db.execute('select sensor_name, temp from cur_temps ORDER BY sensor_name')
return jsonify(cur.fetchall())
接收到的Json
[["BoilerRoom",24.94],["Cylinder1",49.94],["Cylinder2",42.38],["Cylinder3",41.88],["Sensor1",85],["SolidFuelFlow",59],["SolidFuelReturn",41.62]]
我正在尝试获取与Cylinder2 = 42.38相关的数字
我以前使用的js代码如下所示
<script type=text/javascript>
function get_temps() {
$.getJSON("_status",
function (data) {
$('#CylTop').text(data.Cylinder1 + "°")
$('#CylMid').text(data.Cylinder2 + "°")
$('#CylBot').text(data.Cylinder3 + "°")
$('#Solid_flow').text(data.SolidFuelFlow)
$('#Solid_return').text(data.SolidFuelReturn)
$('#BRoom').text(data.BoilerRoom);
console.log(data)
console.log(data.Cylinder1)
}
);
}
setInterval('get_temps()', 5000);
</script>
控制台在浏览器中显示(数据),当我尝试显示任何其他内容时,它就会显示出来。‘console.log(data.Cylinder1)‘,表示未定义。我是一个新手,所以我假设一些索引需要发生,因为它是一个数组,但我有点迷失。任何指导都将不胜感激。
非常感谢
C Dabbs
发布于 2019-01-11 23:06:13
您似乎正在以对象的形式访问data
中的属性。根据响应,它是数组中的一个数组。因此,在以现有方式访问它之前,您必须将其展平。
function get_temps() {
$.getJSON("_status",
function(data) {
let flattendData = data.reduce(function(acc, item) {
return Object.assign({}, acc, {
[item[0]]: item[1]
});
}, {});
$('#CylTop').text(flattendData.Cylinder1 + "°")
$('#CylMid').text(flattendData.Cylinder2 + "°")
$('#CylBot').text(flattendData.Cylinder3 + "°")
$('#Solid_flow').text(flattendData.SolidFuelFlow)
$('#Solid_return').text(flattendData.SolidFuelReturn)
$('#BRoom').text(flattendData.BoilerRoom);
console.log(flattendData)
console.log(flattendData.Cylinder1)
}
);
}
https://stackoverflow.com/questions/54155074
复制相似问题