效果:
記得以前文章寫過 rails autocomplete 插件的使用方法, 那個是基于 prototype 的, 平時Jquery用的最多。。所以必須用jquery 實(shí)現(xiàn) , 這樣的 demo 網(wǎng)上太多。。。。下面介紹在rails 中的一種solution
需要的:
jquery.js
jquery.complete.js
jquery.autocomplete.css
demo :
View:
<script>
$(document).ready(function() {
$("#recipient").autocomplete("/myaccount/res_message", {
delay:10,
minChar: 1,
multiple: true,
parse: function(data) {
return $.map(eval(data), function(item) {
return {
data: item,
value: item.name,
result: item.name
}
});
},
formatItem: function(item) {
return item.show;
}
}).result(function(e, item)
{
$("#recipient").val(item.name);
});
});
</script>
<p><%= text_field_tag :recipient, :id => 'recipient' %></p>
解釋:
#recipient 是對應(yīng)的 id
/myaccount/res_message 對應(yīng)請求的 url
item是參數(shù)
name 和 show 是 返回的變量
action:
def res_message
key = params[:q] if params[:q]
@result = ClientInfo.get_login_name(key, '' , 'key')
respond_to do |format|
format.js # default : res_message.js.erb
end
end
解釋 params[:q] q 是默認(rèn)向后臺發(fā)送的關(guān)鍵字查詢 參數(shù), 并且默認(rèn)的limit 是10 條數(shù)據(jù)
view:res_message.js.erb
<% if @result -%>
<% i=0 %>[
<% for result in @result %>
<% if i==0 %>
{name:"<%= result.login_name %>",show:"<%= result.login_name + " " %>" + "<%= result.sure_name.nil? ? " " : result.sure_name + " " %>"}
<% else %>
,{name:"<%= result.login_name %>",show:"<%= result.login_name + " " %>" + "<%= result.sure_name.nil? ? " " : result.sure_name + " " %>"}
<% end %>
<% i+=1 -%>
<% end -%>]
<% end -%>
解釋: 該view 是返回的數(shù)據(jù),返回的是一個JSON數(shù)組
具體詳細(xì)的可以參考:
http://docs.jquery.com/Plugins/Autocomplete
http://view.jquery.com/trunk/plugins/autocomplete/demo/
posted on 2009-09-04 14:40
fl1429 閱讀(1552)
評論(2) 編輯 收藏 所屬分類:
Rails 、
Jquery