JSON显示为"未定义"用jQuery

时间:2015-07-03 20:34:11

标签: jquery json arduino

我是一个完整的新手,所以也许有些答案需要解释一下。 我试图创建一个包含JSON字符串的小html页面。该页面由Arduino在我的本地网络上托管(经过测试和工作)。要从JSON字符串中检索信息,我已经关注了jQuery的视频教程:JSON AJAX jQuery tutorial

所以,我根据自己的需要稍微调整了草图,但最终出现了问题。在控制台中,我可以看到我获得了JSON,但在页面中,值显示为" undefined"。

以下是代码:

    $(function(){

    var $channels = $('#channels'); //store array

    $.ajax({
     type: 'GET',
     url: 'http://192.168.0.110/ajax_inputs',
     success: function(channels){
     $.each(channels, function(i, channel){ 
        $channels.append('<p>channel # '+ channel.canal +' name: '+               channel.name +'</p>')
    console.log(channels.canal)
            });
        },
    error: function() {
    alert('error loading data')

    }
    });


    });

这是JSON数据:

    channels: [,…]
    0: {name: "NAME 0", status: 1, canal: 0, temperature: -50, setPoint: 5, permission: 1, percentOut: 100}
    1: {name: "NAME 1", status: 0, canal: 1, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    2: {name: "NAME 2", status: 0, canal: 2, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    3: {name: "NAME 3", status: 0, canal: 3, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    4: {name: "NAME 4", status: 0, canal: 4, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    5: {name: "NAME 5", status: 0, canal: 5, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    6: {name: "NAME 6", status: 0, canal: 6, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    7: {name: "NAME 7", status: 0, canal: 7, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}
    8: {name: "NAME 8", status: 0, canal: 8, temperature: 0, setPoint: 5, permission: 0, percentOut: 0}
    9: {name: "NAME 9", status: 0, canal: 9, temperature: -50, setPoint: 5, permission: 0, percentOut: 0}

1 个答案:

答案 0 :(得分:0)

问题是你指的是channels变量,它在json中是一个对象的对象

请参阅this stripped down JSFiddle,其中显示了在循环中访问json的两种方法。

循环在这里:

$.each(channels, function(i, channel){ 
    console.log(channels[i].canal);
    console.log(channel.canal);
});

在第一个输出中,使用循环迭代器channels查询顶级数组i

在第二个中,查询循环变量channel,因此不需要循环迭代器来查看该值。为了记录,看起来你的append()电话会这样做并且应该有用,它只是控制台日志的错误(很容易犯错: - ))

你的错误是你在查询整个数组但是没有迭代器,有效地寻找这个:

channels = { // note the curly brace for an object, which you need for text keys
    'canal': '' // your code looks for this, which doesn't exist
    0: {
    ...
    }
}