1
我是AJAX搜索的新手,也是Rails的新手。我正在嘗試在我的應用的側欄中創建一個搜索表單,以便將其包含在每個頁面中。只有當輸入搜索時,我才需要搜索結果才顯示在當前頁面上。試圖在側邊欄中執行實時AJAX搜索
我有一個'電影'表,我剛開始搜索「標題」列。這是我到目前爲止。現在,搜索不僅僅返回div中的搜索結果,也不返回當前頁面上的任何結果。使用Rails 4.0.0。
_sidebar.html.erb
<aside id="sidebar">
<nav>
<%= form_tag movies_path, :method => 'get', :id => "movies_search" do %>
<center>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
</center>
<div id="cresults_div" style="float:right; width:300px;"><%= render 'cresults' %></div>
<% end %>
<ul style="margin-top: 300px;">
<li class="all-movies">
<%= link_to 'All Movies', movies_path, class: 'button' %>
</li>
<li class="create-movie">
<%= link_to 'Add New Movie', new_movie_path, class: 'button' %>
</li>
</ul>
</nav>
</aside>
movies_controller.rb
def index
@movies = Movie.released
@movies = Movie.search(params[:search])
end
end
movie.rb
def self.search(search)
if search
where('title LIKE ?', "%#{search}%")
else
scoped
end
end
_cresults.html.erb
<h2>Search Results: </h2>
<table>
<tr>
<th>Title:</th>
<th style="width:85px;">Released: </th>
<th>Rating: </th>
</tr>
<% @movies.each do |movie| %>
<tr>
<td><%= link_to movie.title, movie %></td>
<td><center><%= movie.released_on.year %></center></td>
<td><center><%= movie.rating %></center></td>
</tr>
<% end %>
</table>
movies.js
$(function() {
$('#movies_search').submit(->
$.get(this.action, $(this).serialize(), null, 'script')
false
});
$(function() {
$('#movies_search input').keyup(->
$.get($("#movies_search").attr("action"), $("#movies_search").serialize(), null, 'script')
false
});
});
movies.js.erb
$("#cresults_div").html("<%= escape_javascript(render("cresults")) %>");
我也試圖把相同的代碼從電影。 js到application.js中,但結果沒有變化。