最近在rails中驗(yàn)證用戶名唯一性時(shí),使用了原始的xmlHttpRequest時(shí),沒有成功,原因是服務(wù)器端無法response數(shù)據(jù)給客戶端,肯定有解決辦法,但是我目前還沒有解決,于是費(fèi)了點(diǎn)周折使用了rails自帶的ajax方法:observe_field
實(shí)現(xiàn)效果:用戶一邊輸入用戶名,一邊實(shí)現(xiàn)驗(yàn)證
實(shí)現(xiàn)過程:
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, |
說明:
:with 是傳參,對(duì)應(yīng)是name,而非id
controller:
def tip |
說明:
ClientInfo.validate_login_name(name.to_s)是model中驗(yàn)證數(shù)據(jù)的方法
提示:
個(gè)人在做的時(shí)候,無法實(shí)現(xiàn)其效果,也不知道原因,折騰了好久才搞定,是通過firebug發(fā)現(xiàn)form is not defiend錯(cuò)誤,然后google解決的,原因是js的:defaults沒有加入,所以建議大家在調(diào)試js時(shí)使用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,提供一個(gè)demo下載:
http://www.namipan.com/d/7c2280cf8afc1a57dbddf88d9b5962304cd2e91477580100
write by feng |