イベント処理を行わずに、テーブルの値を定期的に自動更新させる。
定期的にpostもしくはgetリクエストを送信してくれるjQueryプラグイン(PeriodicalUpdater)を使用。ダウンロード
index.erb
<script src="js/jquery.periodicalupdater.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.PeriodicalUpdater('./json',{
// オプション設定
method: 'get', // 送信リクエストURL
minTimeout: 10000, // 送信インターバル(ミリ秒)
type: 'json', // xml、json、scriptもしくはhtml (jquery.getやjquery.postのdataType)
multiplier:1, // リクエスト間隔の変更
maxCalls: 0 // リクエスト回数(0:制限なし)
},
function (data){
//dataは上記URLから引き渡され、変更があったか自動で判別される。
//dataに変更があった場合のみ実行
//alert(data);
MyFunc2(data); //セルに値を代入
MyFunc1(); //セルの色付け
});
});
//セルにデータを代入
function MyFunc2(data){
var tr = $("table tbody tr");//全行を取得
for(var i=0, l=tr.length; i<l; i=i+2){
var cells = tr.eq(i).children();//1行目から順にth、td問わず列を取得
//セルに代入
cells.eq(0).text(data[i].time);
cells.eq(1).text(data[i].res1);
cells.eq(2).text(data[i].res2);
cells.eq(3).text(data[i].res3);
cells.eq(4).text(data[i].res4);
cells.eq(5).text(data[i].res5);
cells.eq(6).text(data[i].res6);
}
}
app.rb
get '/json' do
sensors = Sensor.select('time, res1,res2,res3,res4,res5,res6'
).order("time DESC").to_json
end
自動更新するプラグインには、new Ajax.PeriodicalUpdater(container, url[, options])もあるが、onSuccessの時にjQueryを実行できなかった・・・。