在rails中有一种方法可以重新加载具有部分
的div控制器
def home
@events = []
end
def ajax_load_events
...
@band = Band.find_by_name(@artist)
begin
artist = Bandsintown::Artist.new({
:name => @artist
})
@events = artist.events
rescue Bandsintown::APIError
@events = [] #this will ensure that if an error happens from the bandsintown api, we'll catch the error
end
end
HTML
<div class="field disable_color">
<label for="search">Select a Song</label>
<input type="search" name="request[song]" id="request_song" value="" />
</div>
<tbody class="load_events">
<%= render :partial => 'event', :collection => @events %>
</tbody>
部分
<% @events.each_with_index do |event, index| %>
<tr class="gradeU">
<td><%= check_box_tag "instance_selected#{index}", "2"%></td>
<td><%= event.datetime.strftime("%B %d, %Y") %></td>
<td><%= "#{event.venue.name} - #{event.venue.city}, #{event.venue.country}" %></td>
</tr>
<% end %>
的jQuery
$("#request_song").autocomplete({
source: function(req, add){
$.getJSON('/song_ajax/trackName/'+ $("#request_artist").val() + '', req, function(data) {
var suggestions = data.suggestions;
add(suggestions);
});
},
change: function() {
var artist_url = encodeURIComponent($('#request_artist').val().replace(/\./g, ""));
$.getJSON('/ajax_load_events/'+ artist_url + '', function(data) {
});
},
});
基本上我需要使用带有ajax_load_events操作填充的@events数组刷新div #load_events ...任何想法我缺少什么
答案 0 :(得分:7)
在您的控制器中:
def ajax_load_events
respond_to do |format|
format.js
end
end
ajax_load_events.js.erb
$("#load_events").html('<%= escape_javascript(render :partial => "your_partial", :locals => { :events => @events}) %>');
<强>更新强> 的routes.rb
get "/ajax_load_events" => "your_controller#ajax_load_events"
你的.js中的
$.get("/ajax_load_events/", {}, null, "script");