2

下面的代码在循环中从 URL 中获取 Json 对象。

问题是我似乎无法显示返回的 Json 数据。我想显示对象的温度和湿度。

有效的 Json 对象返回正常,但我无法在 HTML div 中显示它。

我看不到任何东西打印到屏幕上。

完整代码:

<html>
<head>
<title>json loop</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>

    <div id="container">
    <div id="div"></div>
        <div id="output">nothing yet</div>
    </div>

<script>
    var previous = null;
    var current = null;
    var data;
    setInterval(function() {
        $.getJSON(
            "https://dweet.io/get/latest/dweet/for/myesp8266", 
            function(json) {
                data = json; 
                current = JSON.stringify(data); 
                $("div").html(data);
                console.log(data);           
                if (previous && current && previous !== current) {
                    console.log('refresh');
                    location.reload();
                }
                previous = current;
        });                       
    }, 2000);   


var output = document.getElementById('output');
output.innerHTML = data ;

</script>
</body>
</html>   
4

2 回答 2

0

你试过这样吗?

setInterval(function() {
    $.getJSON("https://dweet.io/get/latest/dweet/for/myesp8266", 
    function(json) {
        data = json; 
        current = JSON.stringify(data); 
        //$("div").html(data);
        console.log(data);           
        if (previous && current && previous !== current) {
            console.log('refresh');
            location.reload();
        }
        previous = current;
        var output = document.getElementById('output');
        output.innerHTML = current ;
    });                       
}, 2000);  

编辑:

这是一个如何工作的例子:https ://plnkr.co/edit/GI5uzojOOmJNwAc73aXq?p=preview

于 2017-01-15T12:37:47.997 回答
0

您没有将字符串化字符串放入 HTML。用current而不用data

data = json; 
current = JSON.stringify(data); 
$("div").html(current);
console.log(current);           
if (previous && current && previous !== current) {
    console.log('refresh');
    location.reload();
}
previous = current;

编辑

如果您想要温度,请使用:

$("div").html(data.with[0].content.temperature);
于 2017-01-15T12:37:56.103 回答