簡體   English   中英

使用變量無法訪問數據JSON

[英]Unable to access the data JSON, using variables

我試圖使用$. getJson ()獲取有關JSON中某些按鈕狀態的信息$. getJson () $. getJson ()帶有破折號的ID分為兩部分,它們進入了數組regarr。 但是我無法在此查詢中從JSON獲取數據:

data.regarr[0].regarr [1] //regarr is undefined

HTML:

<div class='buttons' id='lamps-fire1'>OFF</div>

我的JSON:

{"lamps":{"fire1":"off","fire2":"off","fire3":"off"},"motor":"on","temperature":"12"}

的JavaScript

$(document).ready(function()
{
    function reloadvalues()
    {
        $('.buttons').each(function ()
        {
                var id=$(this).attr('id');
                var re=/-/;
                var re2=/[a-z0-9]{1,}[^-][a-z0-9]{1,}/ig;
                var regarr=[];
                 regarr=id.match(re2);
                if (id.search(re)==-1)
                {
                    $.getJSON('homeapi.ini','tire=none&id='+encodeURIComponent(id),function (data)
                    {
                    if (data.motor=='off')
                    {
                        $(this).html('OFF.');
                    }
                    else{
                        $(this).html('ON.');
                    }
                    });
                }
                else{
                    $.getJSON('homeapi.ini','',function (data)
                    {
                    if ((regarr[1]!='undefined')||(regarr[0]!='undefined')||(regarr !='undefined'))
                    {
                    if (data.regarr[0].regarr[1]=='off')
                    {
                        $(this).html('OFF.');
                    }
                    else{
                        $(this).html('ON.');
                    }
                    }
                });
                }
            });
    }
    setInterval(function (){
        reloadvalues();
        },5000);
});

也許有人知道出了什么問題?

參考this是不回調函數范圍內相同的,因為它是每個循環內。 在進入子功能之前,您將必須緩存對它的引用。 然后,在你的回調函數塊中的$.getJSON方法,使用存儲引用(在這種情況下,我把它叫做self ),而不是this

$(document).ready(function() {
    function reloadvalues() {
        $('.buttons').each(function() {
            var self = this;

            /* ... */ 
            if (id.search(re) == -1) {
                $.getJSON('homeapi.ini', 'tire=none&id=' + encodeURIComponent(id), 
                function(data) {

                    if (data.motor == 'off') {
                        $(self).html('OFF.');
                    }
                    else {
                        $(self).html('ON.');
                    }
                });
            }
            /* ... */
        });
    }
});​​​

關於引用錯誤,當使用存儲在變量中的屬性名稱時,必須使用[ ]而不是simple來取消引用json對象. 在這種情況下:

更換 data.regarr[0].regarr[1] 帶有data[regarr[0]][regarr[1]]

暫無
暫無

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

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