我正在尝试创建一个动态仪表板,该仪表板每隔x秒刷新一次,以从PHP文件传递新数据。我希望此命令在传递的数据发生更改时发出警报,而不是在刷新数据时发出警报。我正在使用require.js,watch.js和jQuery。我无法发出有关#tfpromo或变量refreshId更改的警报。有没有办法在jQuery,JS或Watch.js中做到这一点?
PHP文件:
$mainbalance = "foo";
echo $mainbalance;
Index.html:
<div id="tfpromo"></div>
<script>
require(['watch', 'jquery'], function(WatchJS, $) {
var watch = WatchJS.watch;
var unwatch = WatchJS.unwatch;
var callWatchers = WatchJS.callWatchers;
$(document).ready(function () {
$("#tfpromo").load("php/dataload.php");
var refreshId = setInterval(function load2(){
$("#tfpromo").load("php/dataload.php");
}, 4000);
watch(refreshId, function(){
alert("balance changed!");
});
});
});
</script>
答案 0 :(得分:1)
watch.js
用于监视JavaScript对象的值。因此,将余额金额放入对象中,然后在.load()
回调中更新对象。
var watch = WatchJS.watch;
var unwatch = WatchJS.unwatch;
var callWatchers = WatchJS.callWatchers;
$(document).ready(function () {
var balanceObj = {balance: 0};
$("#tfpromo").load("php/dataload.php", function() {
balanceObj.balance = $(this).text();
watch(balanceObj, "balance", function() {
alert("Balance changed!");
});
});
var refreshId = setInterval(function load2(){
$("#tfpromo").load("php/dataload.php", function() {
balanceObj.balance = $(this).text();
});
}, 4000);
watch(refreshId, function(){
alert("balance changed!");
});
});
});