railsの勉強 AJAXのサンプル
(clockのことをメモしておきたい。
はじめどんなコードを書いたか。
本にどう書いてあったか。
link_to_remote()で、どう修正したか。
periodically_call_remote()で、どう修正したか。)
「かんたんRuby on RailsでWebアプリケーション開発」の第3章のサンプルを参考にしたがぜんぜん動作しなかった。
8/22現状、以下のようになっている。
views/clock/clock_exec.rhtml
「link_to_remote sample」と書かれたタグをクリックすると、その下にクリックした時点での時刻を取得する部分と、1秒間隔で時刻を更新する部分からできている。
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <%= javascript_include_tag :defaults %> <title>clock</title> <style type="text/css" media="screen"> #left { text-align: right; } #right { text-align: right; } </style> </head> <body> <div id="sample1"> link_to_remoteを使ったサンプル: <%= link_to_remote "link_to_remote sample", :update => :result, :url => 'clock' %> </div> <div id="result">will display time here、if clicking above link</div> <hr/> <div id="param"> periodically_call_remoteを使ったサンプル: <%= periodically_call_remote :update => :result2, :url => 'clock', :frequency => 1 %> </div> <div id="result2"></div> </body> </html>
controllers/clock_controller.rb
上の2つの部分のそれぞれで呼ばれるコントローラ。スレッドで現在の時刻をあらわすフィールドを1秒間隔で更新し、ブラウザに表示する。
class ClockController < ApplicationController def clock Thread.new { @time_str = Time.now.to_s sleep 1 } # @time_str = Time.now.to_s # render(:layout => false) render :patial => "result" end end
views/clock/clock.rhtml
現在の時刻を表示するビュー。clockメソッドのビューなので、clock.rhtmlとなる。
現在の時刻は <%=h @time_str %> です。
views/layouts/clock.rhtml
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <%= javascript_include_tag :defaults %> <title><%= controller.action_name %></title> <style type="text/css" media="screen"> #left { text-align: right; } #right { text-align: right; } </style> </head> <body> <%= @content_for_layout %> </body> </html>
clock_exec.rhtmlは次のようになる。
clock_exec.rhtml
<div id="sample1"> link_to_remoteを使ったサンプル: <%= link_to_remote "link_to_remote sample", :update => :result, :url => 'clock' %> </div> <div id="result">will display time here、if clicking above link</div> <hr/> <div id="param"> periodically_call_remoteを使ったサンプル: <%= periodically_call_remote :update => :result2, :url => 'clock', :frequency => 1 %> </div> <div id="result2"></div>