每天一剂Rails良药之Lightning-Fast JavaScript Auto-completion

本文介绍如何使用Rails框架实现一个快速的自动补全功能。通过将数据预先加载到页面上,当用户输入时,可以迅速匹配并显示建议,提高用户体验。文章详细介绍了实现步骤:配置控制器、封装JavaScript数据及构建搜索页面。
Gmail中你输入收信人地址时会自动搜索并提示,速度很快,因为Gmail不是每次都从后台搜索,而是一开始就
把地址加载到页面中,然后在页面中匹配并搜索。让我们看看怎样在Rails里实现它。

1,准备搜索数据
我们创建app/controllers/book_controller.rb:
[code]
class BookController < ApplicationController

def authors_for_lookup
@authors = Author.find(:all)
@headers['content-type'] = 'text/javascript'
render :layout => false
end

end
[/code]
这里我们设置headers的content-type为text/javascriipt。

2,封装JavaScript数据
我们创建返回的页面app/views/book/authors_for_lookup.rhtml:
[code]
var authors = new Array(<%= @authors.size%>);

<% @authors.each_with_index do |author, index|%>
authors[<%= index %>] = "<%= author.name %>";
<% end %>
[/code]
我们在该rhtml中直接写javascript代码,并用Ruby代码动态取得和填充authors数据

3,写搜索页面
如app/views/book/search_page.rhtml:
[code]
<html>
<head>
<%= javascript_include_tag :defaults %>
<script src="/book/authors_for_lookup" type="text/javascript"></script>
<style>
div.auto_complete {
width: 350px;
background: #fff;
}
div.auto_complete ul {
border: 1px solid #888;
margin: 0;
padding: 0;
width: 100%;
list-style-type: none;
}
div.auto_complete ul li.selected {
background-color: #ffb;
}
div.auto_complete ul strong.highlight {
color: #800;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<label for="author_lookup">Author Search</label>
<input type="text" id="author_lookup" name="author_lookup" />
<div class="auto_complete" id="author_lookup_auto_complete">
</div>
<%= javascript_tag("new Autocompleter.Local('author_lookup',
'author_lookup_auto_complete',
authors,
{fullSearch: true,
frequency: 0,
minChars: 1,
}
);") %>
</body>
</html>
[/code]
Autocompleter.Local在本地(当前页面中)取数据,让我们访问[url]http://localhost:3000/book/search_page[/url]看看效果,很不错哦!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值