2011-03-16 71 views
1

我對編程非常陌生,我目前有一個場地表,它可以通過類型和/或區域使用索引頁上的複選框進行過濾。如何修改我的過濾器表單以使用AJAX?

在railscasts的幫助下,我添加了使用AJAX添加評論到場地的功能。我如何去AJAX化我的過濾器表單?

到目前爲止,我有這樣的:

場館控制器

def index 
    if 
    @venues = Venue.with_type(params[:venuetypes]).with_area(params[:areas]) 
    else 
    @venues = Venue.all 
    end 
end 

場館指數

<div class="filter_options_container"> 
    <%= form_tag '', :method => :get, :id => 'filter_venues' do %> 

    <fieldset class="filter_form_fieldset venuetypes"> 
     <% Venuetype.all.each do |v| %> 
     <%= check_box_tag 'venuetypes[]', v.id, false, :id => "venuetype-#{v.id}" %> 
     <label for="venuetype-<%= v.id %>"><%= v.name %></label> 
     <% end %> 
    </fieldset> 

    <fieldset class="filter_form_fieldset areas"> 
     <% Area.all.each do |a| %> 
     <%= check_box_tag 'areas[]', a.id, false, :id => "area-#{a.id}" %> 
     <label for="area-<%= a.id %>"><p1><%= a.name %></p1></label> 
     <% end %> 
    </fieldset> 

    <div class="filter_form_button"> 
     <p2><input type="submit" value="Filter"/></p2> 
    </div> 
    <% end %> 
</div> 

我試圖在應用了jQuery railscast用同樣的方法使用AJAX添加評論,但太多的peices不適合,並認爲我正在往下走用這個錯誤的路徑,任何人都可以給我任何指針?

非常感謝您的幫助。

回答

2

對於HTML/JS的一面,我會建議使用jQuery Form Plugin - 有很多選擇,但在你的情況下,它可能是那樣簡單:

$('#filter_venues').ajaxForm({ 
    success: function() {/* ...load the response... */} 
}); 

對於Rails的一面,我想請執行下列操作(我做這在我的應用程序,所以我可以保證這是一個有效的參數設置):

分裂您的索引頁轉換成一個模板和部分,像這樣:

index.html.erb:

<!-- ...filter form, some other stuff... --> 
<table> 
    <thead> 
     <!-- all the attributes you feel like showing --> 
    </thead> 
<%= render :partial => 'index.ajax' -%> 
</table> 
<!-- more other stuff... --> 

_index.ajax.erb:

<tbody id="venue-tbody"> 
<% @venues.each do |venue| -%> 
    <tr> 
     <!-- all the attributes you have headers for --> 
    <tr> 
<% end -%> 
</tbody> 

然後,改變你的索引操作,因此呈現爲完整頁面(一/venues.html要求),或僅部分(一/場地阿賈克斯要求):

respond_to do |format| 
    format.html {render :template => 'venues/index.html'} 
    format.ajax {render :template => 'venues/_index.ajax', :layout => false} 
end 

我需要註冊自己的虛擬MIME類型來得到這個工作(在到config/environment.rb):

#Make a fake MIME type for AJAX calls: 
Mime::Type.register 'application/x-ajax', :ajax 

這個設置更詳細的JS例子看起來是這樣的(我認爲這應該是完全功能的。我想。):

function load_new_venues(data, status, request) 
{ 
    $('#venue-tbody').replaceWith(data); 
    //Any event handlers that need to be set for the new HTML elements... 
} 

$('#filter_venues').ajaxForm({ 
    dataType: 'html', 
    success: load_new_venues, 
    url: '/venues.ajax' 
}); 

希望這會有所幫助 - 對不起,如果它變成了一本小說......乾杯!

+0

非常感謝您的回答,它非常棒,正是我想要的! – Dave 2011-03-16 18:32:18