开发者

how to load an html fragment in rails with jquery?

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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜