开发者

how do I reload a div with a rails partial

开发者 https://www.devze.com 2023-04-07 04:02 出处:网络
is there a way in rails to reload a div with a partial Controller def home @events = [] end def ajax_load_events

is there a way in rails to reload a div with a partial

Controller

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>

partial

<% @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) {

        });
    },
});

Basically i need the div #load_events be refreshed with the @events array that is populated with the ajax_load_events action ...any ideas what i am missing


In your controller:

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}) %>');

Update: routes.rb

get "/ajax_load_events" => "your_controller#ajax_load_events"

in your .js

 $.get("/ajax_load_events/", {}, null, "script");
0

精彩评论

暂无评论...
验证码 换一张
取 消