在rails中 Rendering Partials through Ajax
之前做。net的时候,自己做了一个showcontent的插件,用来加载页面的局部partial
之前采用的是ashx的方式
但rails里面不太方面,今天找到一个比较好的方法,试验成功
起初网上找到一个解决方案
HTML Tab <li class='StreamTab StreamTabRecent active'> <%= link_to 'Most Recent', mostrecent_schools_path, :remote => true, :class => 'TabText' %> </li> <div id='ContentBody'> <div id='ajax'></div> <%= render 'users/microposts', :microposts => @microposts %> </div> School Controller class SchoolsController < ApplicationController def mostrecent @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page]) respond_to do |format| format.html format.js end end end
Most Recent JS
$("#ContentBody").html('<%= escape_javascript(render :partial => "users/microposts" )%>');
Routes
resources :schools do
collection do
get :mostrecent
end
end
原文:http://stackoverflow.com/questions/17246411/ajax-call-to-render-partial-in-rails-3
但这个方法不太好,会有一些特殊字符过滤问题
后来发现这个方法不错
def mostrecent @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page]) respond_to do |format| format.json { render :json => {:success => true, :html => (render_to_string 'users/microposts')} } format.html { } end end
$('.TabText').live 'ajax:success', (event,data) -> $('#ContentBody').html(data.html) if(data.success == true)
通过locals可以给partial传直
render_to_string(:partial => 'my_partial', :layout => false, :locals => {:my_object => my_value})
利用这个方式可以做无刷新的分页技术,而且相当方便