我已经完成了使用Ruby on Rails的搜索应用程序的工作。但是现在我需要在其中使用AJAX,以便搜索操作不会重新加载新页面。这是application.js文件:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
$(function(){
$("#autoc").submit(function(){
$.get(this.action, $this.serialize(),null,"script")
return false;
});
});
这是查看页面:
<h4>Results for your search.</h4>
<br>
<br>
<div id="container">
<% if !(@results.nil?)%>
<% for prod in @results %>
<div class="product">
<div class="image"><%= image_tag(prod.image, :alt => "logo", :size => "75x75") %> </div>
<div class="name"><h3> <%= prod.name %> </h3></div>
<div class="price"><h5>Old Price:</h5><%= prod.maxprice%></div>
<div class="price"> <h5>New Price:</h5><%= (prod.maxprice)-(prod.maxprice * prod.discount / 100) %></div>
</div>
<% end %>
<% else %>
<div class="notice"><%= flash[:alert] %></div>
<% end %>
</div>
这是我的控制器代码:
def index
@init = Sunspot.search(Clothes) do
paginate :page => params[:page], :per_page => 24
order_by :maxprice
end
@first = @init.results
end
def show
if params[:name] == ""
@search = []
else
@search = Sunspot.search(Clothes) do
fulltext params[:name]
paginate :page => params[:page], :per_page => 24
order_by :maxprice
end
@results = @search.results
end
flash[:notice] = "Enter something!"
end
def autocomplete
list=[]
@res = Clothes.search do
fulltext params[:term]
paginate :page => 1, :per_page => 100
order_by :maxprice
end
@rest = @res.results
@rest.each do |brand|
list << {"label"=>brand.name, "value"=>brand.name, "id"=>brand.id}
end
respond_to do |format|
format.json{render :json=>list.to_json, :layout=>false}
end
end
最佳答案
您只需要设置remote: true
即可启用ajax。
here提供了更多参考。