JavaScriptHelper之 periodically_ajax_tag

尚声
2023-12-01

     periodically_call_remote 标签用于周期性触发交互操作,它基于计时器实现 RoR 允许用户自行指定计时器的周期。 periodically_call_remote 标签主要用于维护持续性的 Ajax 交互操作

 

R 1 :创建 controller 控制器类 PeriodicallyAjaxTagController ,以及相应的模板 index.rhtml

controller 控制器类 PeriodicallyAjaxTagController 对应的文件为 periodically_ ajax_tag_controller.rb ,位于 app/controllers 目录下。

index.rhtml 文件位于 app/views/periodically_ajax_tag 目录下。

P: 可以使用命令 ruby script/generate controller periodically_ajax_tag index 完成创建。


R 2 :编辑 periodically_ajax_tag_controller.rb 文件,完整代码如下。

1    class PeriodicallyAjaxTagController < ApplicationController

2        before_filter :set_charset

3  

4        def set_charset

5            @headers["Content-Type"] = "text/html; charset=utf-8"

6        end

7  

8        def index

9            render(:template => "periodically_ajax_tag/index")

10      end

11 

12      def time_show

13          render(:text => Time.now)

14      end

15   end

2~6 行:设定输出模板文件的字符集为 utf-8

8~10 行:显式指定模板文件

12~14 行:获得当前时间

 

R 3 index.rhtml 文件, 代码如下:

1    <html>

2      <head>

3        <title>periodically_to_remote 测试 </title>

4        <%= javascript_include_tag "prototype" %>

5      </head>

6      <body>

7        <p>

8          <%= periodically_call_remote(

                                                 :update => :time_show_roll,

9                                                :url => {:action => :time_ show},

10                                              :frequency => 1) %>

11         <div id="time_show_roll"></div>

12       </p>

13     </body>

14   </html>


4 行:使用 javascript_include_tag 标签来包含 prototype.js 文件。

8~10 行:使用 periodically_call_remote 标签定义计时器 :update 参数项用于指定更新区域的 id :url 参数项指定了所要请求的行为方法 :frequency 参数项用于指定更新周期 ,本例中指定更新周期为 1 。本段代码生成的 HTML 代码如下。

<script type="text/javascript">

//<![CDATA[new PeriodicalExecuter(function() {new Ajax.Updater ('time_show_roll', '/periodically_ ajax_tag/time_show', {asynchronous: true, evalScripts:true})}, 1)//]]>

</script>

11 行:定义了列表更新区域,响应结果会显示在该处。

 

 

R 4 :测试 ,在 IE 地址栏中输入 http://localhost:3000/periodically_ajax_tag

 

 类似资料: