最近在rails中驗證用戶名唯一性時,使用了原始的xmlHttpRequest時,沒有成功,原因是服務器端無法response數據給客戶端,肯定有解決辦法,但是我目前還沒有解決,于是費了點周折使用了rails自帶的ajax方法:observe_field
實現效果:用戶一邊輸入用戶名,一邊實現驗證
實現過程:
rhtml:
<span id="result" ></span> <input name="loginname" type="text" id="ctl00_main_content_txtLogin" class="textbox" style="width:120px;" /> <%= observe_field(:ctl00_main_content_txtLogin, :frequency => 0.2, :update => :result, :with => 'loginname', :url => {:action => :tip }) %> |
說明:
:with 是傳參,對應是name,而非id
controller:
def tip name = params[:loginname] if !ClientInfo.validate_login_name(name.to_s).nil? render :text=>'該用戶已經存在' else render :text => '' end end |
說明:
ClientInfo.validate_login_name(name.to_s)是model中驗證數據的方法
提示:
個人在做的時候,無法實現其效果,也不知道原因,折騰了好久才搞定,是通過firebug發現form is not defiend錯誤,然后google解決的,原因是js的:defaults沒有加入,所以建議大家在調試js時使用firebug!
ref:
http://www.nabble.com/observe_field-gets-%22Form-is-not-defined%22-td4649511.html
http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/observe_field
如果想更升入的了解observe_field,提供一個demo下載:
http://www.namipan.com/d/7c2280cf8afc1a57dbddf88d9b5962304cd2e91477580100
posted on 2009-04-28 18:02
fl1429 閱讀(774)
評論(0) 編輯 收藏 所屬分類:
Rails