2015-07-03 138 views
0

我是一个完整的新手,所以也许一些答案必须解释一下。 我想做一个包含JSON字符串的小型html页面。该页面由我的本地网络上的Arduino托管(已测试和正在运行)。为了从JSON字符串中检索信息,我遵循了jQuery的视频教程:JSON AJAX jQuery tutorialJSON显示为“undefined”与jQuery

所以,我对草图进行了一些调整,以适应我的需求,但最后却出现了错误。在控制台中,我可以看到我获得了JSON,但在页面中,该值显示为“未定义”。

下面是代码:

$(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} 

回答

0

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

请参阅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: { 
    ... 
    } 
} 
+0

起初,它只是我使用的append()函数,并且它在页面上显示“undefine”。从教程中做同样的事情,一切都很好,直到我尝试访问json中的对象... – Nitrof