繁体   English   中英

Rails:通过Ajax渲染部分

[英]Rails: Rendering Partials through Ajax

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

HTML标签

<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>

学校管理员

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

最近的JS

$("#ContentBody").html('<%= escape_javascript(render :partial => "users/microposts" )%>');

路线

  resources :schools do
    collection do
        get :mostrecent
    end
  end

请参阅我之前的帖子的答案。 这将让您了解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')} }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM