[英]Trigger event on change in returned data from getJSON call
我有一个getJSON函数,当前正在调用一次,然后使用setInterval()函数来侦听Thingspeak.com频道供稿,该供稿可能随时更改。
当返回的数据field1的值为'1'时,我想在getJSON函数之外的jQuery代码中触发一个事件。 如果值为“ 0”,则应关闭事件。 到现在为止还挺好。 但是由于getJSON间隔几秒钟在监听频道供稿,因此它将一遍又一遍地触发事件(timer()函数)。
如何让getJSON事件“在后台运行”,并且仅在从通道供稿返回的数据实际发生更改时才触发? 返回的数据还具有一个字段,该字段具有用于数据条目的唯一ID(entry_id),因此可以侦听此值的更改。
当前正在运行此代码:
$(document).ready(function() {
getUpdates();
setInterval('getUpdates()',400);
});
function getUpdates() {
$.getJSON('http://api.thingspeak.com/channels/xxx/feed/last.json?callback=?', {key: "xxx"}, function(data) {
if(data.field1 == '1') {
// trigger timer function on
} else if(data.field1 == '0') {
// trigger timer function off
}
});
function timer() {
// Starts a timer countdown in a div
}
这是该代码的第二个版本,可能会提供更多信息:
$(document).ready(function() {
getUpdates();
setInterval('getUpdates()',400);
});
function getUpdates() {
var entries = new Array();
$.getJSON('http://api.thingspeak.com/channels/xxx/feed/last.json?callback=?', {key: "xxx"}, function(data) {
if ($.inArray(data.entry_id,entries) === -1) {
//New entry, add the ID to the entries array
entries.push(data.entry_id);
//Check if the div should be visible or not
if(data.field1 == '1') {
$(".desc").show();
} else if(data.field1 == '0') {
$(".desc").hide();
}
} else if ($.inArray(data.entry_id,entries) > -1) {
// Same entry as previous call, do nothing.
}
});
}
<div class="desc"></div>
这仍然不起作用,因为它似乎没有更新entrys数组。
这是一个未经测试的近似逻辑(毕竟我无法使用正确的数据访问提要)。 让我知道它是否能引导您朝正确的方向发展。
var timerSet = 0;
function startTimer(){
timerSet = 1;
// start the 1-minute timer and show feedback to user
}
function stopTimer(){
timerSet = 0;
// stop the 1-minute timer and show feedback to user
}
function getUpdates() {
var entries = new Array();
$.getJSON('http://api.thingspeak.com/channels/xxx/feed/last.json?callback=?', {key: "xxx"}, function(data) {
if ($.inArray(data.entry_id,entries) === -1) {
//New entry, add the ID to the entries array
entries.push(data.entry_id);
// check which state the system is in and manage the 1-minute timer
if(data.field1 == '1' && timerSet === 0) { // if 1-minute timer not running already - start it
startTimer();
} else if(data.field1 == '0' && timerSet === 1) { // if 1-minute timer running already - stop it
stopTimer();
}
}
});
}
$(document).ready(function() {
// getUpdates(); don't need this: function will be called in 400ms anyway
setInterval('getUpdates()',400);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.