Rails:通过Ajax渲染部分

我有一个带有选项卡的页面,我想在单击选项卡时通过ajax呈现不同的部分。 我有一些代码,但我不认为这是最有效的方式。 我希望是否有人可以帮助我使用已经存在的代码,或者如果有更简单的方法我会非常感激。 谢谢!

HTML标签

  • true, :class => 'TabText' %>
  • @microposts %>

    学校管理员

     class SchoolsController  3, :page => params[:page]) respond_to do |format| format.html format.js end end end 

    最近的JS

     $("#ContentBody").html(' "users/microposts" )%>'); 

    路线

      resources :schools do collection do get :mostrecent end end 

    请参阅我之前的post的答案。 这将让您了解Rails中的AJAX:在完成模型#update后显示模型#new form

    你可以做的是在动作中渲染一个json并将部分传递给json。

     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 

    您可以访问js中的json(即javascript / coffeescript文件,例如mostrecent.js或mostrecent.js.coffee)并替换当前元素。

     $('.TabText').live 'ajax:success', (event,data) -> $('#ContentBody').html(data.html) if(data.success == true) 

    普拉斯文的回答是正确的。 返回和执行JS可能看起来很简单,但它使调试变得更加糟糕 – 如何在JS中设置通过AJAX返回的断点? 相反,您应该在页面中包含所有JS并仅返回数据。

    我正在使用rails 4.2和@prasvin的答案指出我正确的方向,但当我使用

     format.json { render :json => {:success => true, :html => (render_to_string 'instruments')} } 

    我会收到错误“缺少模板……工具……”

    经过一番阅读后,我发现这条评论使用了render_to_string来给出部分视图错误 。 @marcel提到你需要指定文件是partial,partial:’instruments’,如下所示:

     format.json { render :json => {:success => true, :html => (render_to_string partial: 'instruments')} }