weixin_33695450 2016-03-20 00:39 采纳率: 0%
浏览 55

Javascript和Ajax调用

I have a couple questions about loading javascript after an ajax call.

So I'm using ruby on rails and I have different pages loaded through ajax calls (I do this because I have an audio player that I want to keep playing as pages reload).

The problem is, when I change pages with ajax, the javascript doesnt reload (or work) on the new page.

For example, I have a grid system that sets the height of the grid image based on the width with javascript. The script doesnt work unless I reload the page or I put the script in a script tag at the bottom of the html file.

Is there any way to reload the javascript? I've tried location.reload() but that just refreshes the page and defeats the whole purpose. Thank you!

Here is an example:

show.js.erb

$('#results').html("<%= escape_javascript(render partial: 'songs/showcard', locals: { song: @song }) %>");

songs_controller

  def show
    respond_to do |format|
      format.js
      format.html
    end
  end

link to show page

<%= link_to song, remote: true do %><%= song.title %><% end %>

Here is the cardSize function I'm loading a in file called cardSize.js

$(document).ready(function cardSize () {
  var cardWidth = $('.card-image').width();
  $('.card-image').css({
    'height': cardWidth + 'px'
  });
});
  • 写回答

2条回答 默认 最新

  • weixin_33739523 2016-03-20 00:53
    关注

    In the UJS file show.js.erb you need to invoke the global functions that control the view / grid.

    For example, if the global method for controlling the height etc. is implement_grid(), then, the file should look like:

    $('#results').html("<%= escape_javascript(render partial: 'songs/showcard', locals: { song: @song }) %>");
    implement_grid();
    

    Items added to the DOM dynamically do not necessarily trigger any actions unless you specify them. You could look at binding listeners to html modifying on the div/table (grid) which would then invoke the height changes you're looking for if you'd rather keep that code out of the UJS files.

    Also, that $('#results') can be considerably shortened:

    $('#results').html("<%= j render 'songs/showcard', song: @song %>");
    
    评论

报告相同问题?