What's the most Rails-y way to return different HTML to AJAX?
I've got a search box on my site that typically works via AJAX. The results are returned with very little markup and dropped into an existing div.
However, it's possible that people may do searches via regular page requests. For example, in Google Chrome's address bar, type stackoverflow.com
and hit tab. Google has detected that SO has a search box and Chrome will now use it for your search.
The same thing can happen on our site. In that case, I'd like to respond with a full HTML page, not a snippet.
I know Rails controllers can use respond_to
, but as I understand it, that means "what type of content did the user ask for - html? xml? json?" In this case, both requests need HTML, just different amounts of it.
Is there a canonical Rails way to differentiate responses with the same content type? If not, can anyone suggest a good pat开发者_StackOverflow中文版tern?
Update
This is what I'm doing now in the search
method of my Help controller, which has a default of layout false
. (I'm not changing that, because it is correct for other methods on the controller.)
# All non-AJAX searches should get a layout
unless request.xhr?
render :search, :layout => 'search'
end
I believe you can just ask the request itself if it's ajaxy and respond accordingly (although I've never actually done this myself):
if request.xhr?
...
精彩评论