`
hideto
  • 浏览: 2666767 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

    博客分类:
  • Ruby
阅读更多
Gmail中你输入收信人地址时会自动搜索并提示,速度很快,因为Gmail不是每次都从后台搜索,而是一开始就
把地址加载到页面中,然后在页面中匹配并搜索。让我们看看怎样在Rails里实现它。

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

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

end

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

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

<% @authors.each_with_index do |author, index|%>
    authors[<%= index %>] = "<%= author.name %>";
<% end %>

我们在该rhtml中直接写javascript代码,并用Ruby代码动态取得和填充authors数据

3,写搜索页面
如app/views/book/search_page.rhtml:
<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>

Autocompleter.Local在本地(当前页面中)取数据,让我们访问http://localhost:3000/book/search_page看看效果,很不错哦!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics