通过Rails在Web应用程序中使用Ajax(1)(2)
Ajax 动态搜索 Prototype.js 提供了观察页面上的字段和表单的功能。我利用这种功能观察一个文本字段,可在其中输入部分菜谱名。然后运行 RecipesController 的
Ajax 动态搜索
Prototype.js 提供了观察页面上的字段和表单的功能。我利用这种功能观察一个文本字段,可在其中输入部分菜谱名。然后运行 RecipesController 的搜索方法,输出放在文本字段下方的 标记中。首先从更新的 RecipesController 开始,如清单 8所示。
清单 8. Recipes_controller.rb
class RecipesController < ApplicationController
...
def index
end
def search_ajax
@recipes = Recipe.find( :all,
:conditions => [ "name LIKE ?",
"%#{params[:recipe][:name]}%" ] )
render :layout=>false
end
end |
index() 方法呈现 HTML 表单。search_ajax() 方法根据搜索参数查找菜谱并把数据发送给 ERB 模板格式化。index.rtml 模板如清单 9所示。
清单 9. Index.rhtml
<%= javascript_include_tag :defaults %>
<%= form_tag nil, { :id => 'search_form' } %>
<%= text_field 'recipe', 'name' %>
<%= end_form_tag %>
|






