2
我已經從RailsCasts第240號轉載了代碼。我不知道爲什麼使用此代碼Ajax請求不起作用。搜索功能與常規方法(重新加載頁面)一起工作,而不是通過Ajax。排序功能根本不起作用。搜索,按AJAX排序
我已經包含下面的JavaScript庫:
- 的application.js
- jQuery JavaScript庫V1.6.2
- jQuery UI的1.8.15
- jQuery.rails.js
- 的jQuery TinySort v1.1.0
如果您需要更多信息pl放心讓我知道。我希望你能幫助我解決問題。
users_controller.rb
def index
@users = User.search(params[:search]).order(sort_column + " " + sort_direction)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end
def sort_column
User.column_names.include?(params[:sort]) ? params[:sort] : "lastname"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
index.html.erb
<h1>Listing users</h1>
<%= form_tag users_path, :method => 'get', :id => "users_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="users">
<%= render 'users' %>
</div>
<% end %>
_users.html.erb
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<table class="pretty">
<tr>
<th><%= sortable "Last name" %></th>
<th><%= sortable "First name" %></th>
</tr>
<% for user in @users %>
<tr>
<td><%= user.lastname %></td>
<td><%= user.firstname %></td>
</tr>
<% end %>
</table>
index.js.erb的
$("#users").html("<%= escape_javascript(render("users")) %>");
users_helper.rb
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
的application.js
$(function() {
$("#users th a").live("click", function() {
$.getScript(this.href);
return false;
});
$("#users_search input").keyup(function() {
$.get($("#users_search").attr("action"), $("#users_search").serialize(), null, "script");
return false;
});
});
謝謝您的幫助!