2015-07-03 87 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