Sorry for this newbie question, I am trying to display a simple alert box through Ajax when my galleries/show view is loaded. (After I would like to display content instead of this alert box)
Here is my code so far:
galleries_controller.rb
def show
@gallery = Gallery.find(params[:id])
respond_to do |format|
format.js
开发者_运维百科 format.html # show.html.erb
end
end
application.js
// Tell Rails to use .js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
$(document).ready(function(){
// How can I load show.js.erb ?
$('body').load()
});
show.js.erb
alert('ajax works!');
I can't figure how to make it works. Thanks a lot for your help.
Remote everything in application js
in show.html.erb
<%= link_to "Get Gallery", gallery_url(@gallery), :remote => true %>
Reload /galleries/show/:id Click the link
Rails returns show.js.erb
(after evaluation) when you hit Gallery#show
from an AJAX call. So, you can get the contents returned with jQuery.get
:
$.get({'gallery/show/some_id_number', dataType: script});
The dataType: script
property will cause jQuery to execute what's returned (i.e. the contents of the evaluated show.js.erb
).
精彩评论