rails笔记 ajax
ajax web2.0
要使用ajax,先要在页面中包含 <%=javascript_include_tag "prototype"%>
ajax的指令如下
link_to_remote
例子如下
<%= link_to_remote("Do the Ajax thing",
:update => 'mydiv',
:url => { :action => :say_hello }) %>
<div id="mydiv">This text will be changed</div>
第一个参数为link的文本第二个参数为更新的元素的的id(div,span font等都可以) 第三个参数为远程的url(url_for语法),注意这个url要把layout关闭
form_remote_tag
例子如下 <%= form_remote_tag(:update => "update_div", :url => { :action => :guess } ) %> <%= text_field_tag :guess %> <%= submit_tag "Post form with AJAX" %> <%= end_form_tag %>
参数有:update更新的元素id :url同上 更多参数查api ??? 为什么api上的参数不一样呢
observers
例子如下
<%= text_field_tag :search %>
<%= observe_field(:search,
:frequency => 0.5,
:update => :results,
:url => { :action => :search }) %>
:frequency是指定更新的频率,当发现输入字段有改变时候会自动提交修改到对应的action,把返回值搞下来更新
??? 注意 这里在action端使用了使用了request.raw_post || request.query_string 似乎还不是很明白这个用法
periodic update
例子如下 <%= periodically_call_remote(:update => 'process-list', :url => { :action => :ps }, :frequency => 2 )%>
参数同上
Dom接口 !!!看看javascript的文档
rails单独提供了一套javascript的api来操作Dom接口
$(id)
Pass the $( ) method a string, and it returns the DOM element with the given id. Otherwise it returns its argument. (This behavior means you can pass in either an element’s id= attribute or the element itself and get an element returned.)
$('mydiv').style.border = "1px solid red"; /* sets border on mydiv */
Element.toggle(element, ...)
Element.toggle( ) toggles whether the given element (or elements) are shown. Internally, it switches the value of the CSS display attribute between ’inline’ and ’none’.
Element.toggle('mydiv'); /* toggles mydiv */
Element.toggle('div1', 'div2', 'div3'); /* toggles div1-div3 */
Element.show(element, ...)
Element.show( ) ensures all elements it receives as parameters will be shown.
Element.show('warning'); /* shows the element with id 'warning' */
Element.hide(element, ...)
Opposite of Element.show( ).
Element.remove(element)
Element.remove( ) completely removes an element from the DOM.
Element.remove('mydiv'); /* completely erase mydiv */
Insertion methods
The various insertion methods make it easy to add HTML fragments to existing elements. They are discussed in Section 18.4, Replacement Techniques, on page 389.
javascript效果
javascript效果需要额外include "effects"包,所以一共include 两个包
<%= javascript_include_tag "prototype", "effects" %>
调用效果一般通过Effect.xxx(element) 可以传入一个代表id的string,或者使用this表明当前对象