简体   繁体   中英

rails 5 render on JS request

Hi am trying to render a index page particular part from same index controller response i am don't know is it possible or not..

This is Index Controller code

def index
@songs = Song.language_fillter(params[:language]).category_fillter(params[:category]).paginate(:page =>params[:page], :per_page => 6)
@languages = Song.distinct.select(:language)
@category = Song.distinct.select(:category)
respond_to do |format|
  format.html{}
  format.js{ render partial: 'songs/songshow', :collection => @songs, :layout => false}
end
end

index.html.erb

<ul class="nav justify-content-center mt-3">
 <li class="nav-item">
  <select class="custom-select song_filter" id="language_filter">
  <option value=""selected>Language</option>
  <% @languages.each do |lang| %>
    <option value="<%= lang.language %>"><%= lang.language %></option>
  <% end %>
</select>
</li>
<li class="nav-item">
   <select class="custom-select song_filter" id="category_filter">
     <option value="" selected>Category</option>
     <% @category.each do |cat| %>
     <option value="<%= cat.category %>"><%= cat.category %></option>
     <% end %>
   </select>
 </li>
</ul>
   <div class="container">
 <div class="mt-5 row" id="songs_display">
     <%= render partial: 'songshow' %>
 </div>

in this i like to change the content of id songs_display with CoffeeScript

$(document).on 'change', '.song_filter', () ->
  language = $('#language_filter').val()
  category = $('#category_filter').val()
  console.log language+" "+category
  $.ajax '/songs',
  type:'GET'
  data:{language: language,category: category }
  dataType: 'text'
  success: (data,textStatus,jqXHR) ->
    $('#songs_display').html data

by this i like to it should render only the partial but it render layout also but i want only it should render partial. is it possible..

Hi i have an one idea to do this. you are using respond_to blog. you can create a one coffee file same as Controller action name and put your coffee render inside like this

index.js.coffee

$('#songs_display').html("<%= j render partial: 'songs/songshow', :collection => @songs %>");

change index action respond_to

  format.js{}

and your js request

  $.ajax '/songs',
  type:'get'
  data:{language: language,category: category }
  dataType: 'script'

i hope this will work for you. if any issue please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM