实现实时的搜索

[size=large][/size][color=green]实现实时的搜索
a live search

如果你想着在你的页面进行实时的搜索--就是到你在输入不同关键字的时候,查询的解果将发生变化。

使用 rails 的ajax 辅助方法 创建一个实时 搜索
数据库的迁移
db/migrate/001_create_books.rb:

class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.column :title, :string
end

Book.create :title => 'Perl Best Practices'
Book.create :title => 'Learning Python'
Book.create :title => 'Unix in a Nutshell'
Book.create :title => 'Classic Shell Scripting'
Book.create :title => 'Photoshop Elements 3: The Missing Manual'
Book.create :title => 'Linux Network Administrator's Guide'
Book.create :title => 'C++ Cookbook'
Book.create :title => 'UML 2.0 in a Nutshell'
Book.create :title => 'Home Networking: The Missing Manual'
Book.create :title => 'AI for Game Developers'
Book.create :title => 'JavaServer Faces'
Book.create :title => 'Astronomy Hacks'
Book.create :title => 'Understanding the Linux Kernel'
Book.create :title => 'XML Pocket Reference'
Book.create :title => 'Understanding Linux Network Internals'
end

def self.down
drop_table :books
end
end

接着,使用   script.aculo.us and Prototype
包含到布局中去。
app/views/layouts/books.rhtml:

<html>
<head>
<title>Books</title>
<%= javascript_include_tag :defaults %>
</head>
<body>
<%= yield %>
</body>
</html


创建包含index and search 方法的控制器。 search方法对从index视图发过来的ajax调用做出响应。
app/controllers/books_controller.rb:

class BooksController < ApplicationController

def index
end

def get_results
if request.xhr?
if params['search_text'].strip.length > 0
terms = params['search_text'].split.collect do |word|
"%#{word.downcase}%"
end
@books = Book.find(
:all,
:conditions => [
( ["(LOWER(title) LIKE ?)"] * terms.size ).join(" AND "),
* terms.flatten
]
)
end
render :partial => "search"
else
redirect_to :action => "index"
end
end
end


index.rhtml  视图显示了查询字段,并使用observe_field 这一JavaScript 辅助方法在字段中定义一个观察者。 
app/views/books/index.rhtml:

<h1>Books</h1>

Search: <input type="text" id="search_form" name="search" />

<img id="spinner" src="/images/indicator.gif" style="display: none;" />

<div id="results"></div>

<%= observe_field 'search_form',
:frequency => 0.5,
:update => 'results',
:url => { :controller => 'books', :action=> 'get_results' },
:with => "'search_text=' + escape(value)",
:loading => "document.getElementById('spinner').style.display='inline'",
:loaded => "document.getElementById('spinner').style.display='none'" %>


最后,创建一个局部模版, 将查询结果显示为一个书本标题列表。
app/views/books/_search.rhtml:

<% if @books %>
<ul>
<% for book in @books %>
<li>
<%= h(book.title) %>
</li>
<% end %>
</ul>
<% end %>
[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值