I am wondering how I may jQuery.load
an HTML fragment returned by a model's show
action. For example, $("#container").load("/posts/34")
. The problem with this is that it returns the view I want embedded in the layout, as if I were to visit that url in the browser. I only want the Post
's show
HTMl fragment.
Thanks!
Clarification: I want the show
view to continue to render within the application layout when going to the show
action in my browser. I'm merely trying to figure out how to fetch only the html of the show
view for when I want to load it asynchronously with jQuery. I have seen guides in which they create show.js.erb
and then render the html view there, but it seems pretty messy to me, escaping all of that html for javascript. If this is the accepted and proper way of doing this though I guess I'll follow the standard. I was just wondering if it were possible to only fetch the html of a particular view.
You can use :layout => false in your render statement to return the fragment without the layout:
def show
...
render(:layout => false) if request.xhr?
end
You could pass a GET parameter in the URL and put a condition in your controller:
def show
render(:layout => false) if params['partial'] == 'true'
end
And javascript:
$('#container').load('/posts/34?partial=true')
If you want to support regular and AJAX requests you'll want to use a respond_to
block.
Like so
respond_to do |format|
format.html # renders index.html.erb automatically
format.js { render 'show', :content_type=>'text/html', :layout=>false }
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With