我最近一直在調整Z-Wave,並試圖製作一個包含/排除其產品的頁面。但它不太好。我試圖檢查是否存在JSON鍵,然後將其顯示在頁面上。我得到javascript檢查JSON密鑰是否存在並顯示值
TypeError: data.controller is undefined
下面是代碼:
window.setInterval(function(){
getData();
}, 2000);
function getData()
{
var milliseconds = (new Date).getTime();
var time = milliseconds.toString().substr(0, milliseconds.toString().length - 3) ;
$.postJSON("http://192.168.1.102:8083/ZWaveAPI/Data/" + time, function(data) {
if(data.controller.lastExcludedDevice.value) alert("EXCLUDED SOMETHING");
if(data.controller.lastIncludedDevice.value) alert("INCLUDED SOMETHING");
});
}
$.postJSON = function(url, data, callback, sync) {
// shift arguments if data argument was omited
if (jQuery.isFunction(data)) {
sync = sync || callback;
callback = data;
data = {};
};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: callback,
error: callback,
async: (sync!=true)
});
};
JSON:
{
"controller.data.controllerState": {
"value": 0,
"type": "int",
"invalidateTime": 1424781697,
"updateTime": 1425338938
},
"controller.data.lastIncludedDevice": {
"value": 42,
"type": "int",
"invalidateTime": 1424781697,
"updateTime": 1425338938
},
......
任何幫助是極大的讚賞。
我建議閱讀[訪問/處理(嵌套的)對象,數組或JSON(http://stackoverflow.com/questions/11922383/接入過程嵌套對象陣列或 - JSON)。閱讀有關對象的教程也可能有所幫助:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – 2015-03-02 23:33:09
考慮使用'parseInt(Date.now()/ 1000,10)'來在幾秒鐘內獲得時間戳 – 2015-03-02 23:35:12