簡體   English   中英

無法打印Json對象

[英]Unable to print Json object

下面的代碼通過循環從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>   

你有這樣嘗試過嗎?

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

您沒有將字符串化的字符串放入HTML。 使用current data而不是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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM