我有一个非常简单的 Ruby On Rails 应用程序,前端带有 bootstrap 3:我有交易,每个交易都有很多机会。
在每个交易页面(交易 1 的 url 类似于 myapp.com/id=1),我想要一个文本链接,上面写着“查看交易的机会”,并且必须在单击 Bootstrap 中的内容外观时触发模态。
非常基本但出于特定原因,我希望通过 Ajax 加载模态的内容。(当用户加载交易页面时内容不可见,但只有当他们单击链接时才可见 '查看交易机会'
我在网上找到了许多关于 Rails4/ajax/Forms 和其他 Ajax 内容的资源,但不是通过 Ajax 在模态内简单的“显示内容/文本”。应该很容易,但我卡住了。
controller/deals_controller.rb
def showcase
deals = Deal.friendly.find(params[:id])
respond_to do |format|
format.html # showcase.html.erb
format.json { render json: @deal }
end
end
def show_opportunities
@opportunities = Opportunity.where('deal_id = ? AND deal_type = ?',
@deal.id, "high tech").first
respond_to do |format|
format.js
end
end
app/views/deals/showcase.html.erb
this is the beginning
<%= render 'deals/deal_info_zone' %>
this is the end
views/deals/_deal_info_zone.html.erb
<div id="zoneA">
<div style="color:red;padding-top: 150px;">
<%= link_to "view infos of Opportunities", deal_opportunities_modal_path, remote: true %>
</div>
</div>
这是我想通过 ajax 触发的模式:views/deals/opportunity_modal
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<%= @opportunity.name %> <br/>
</div>
</div>
</div>
</div>
routes.rb
match '/deals/:id', # this is the Deal page
to: 'deals#showcase',
via: 'get',
as: :deal_page
match '/opportunity_modal',
to: 'deals#show_opportunities',
via: 'get',
as: :deal_opportunities_modal
我是 RoR 的菜鸟,从来没有用过 ajax,也许是 ujs...我觉得它缺少 javascript 代码和 xhr 请求之类的东西...
当前情况是这样的:当我进入交易页面(前页面/deal id=1)时,文本链接“查看机会信息”。并且浏览器指向 http://localhost:3000/opportunity_modal但是当我点击它时它不会触发任何东西。什么都没发生。在 firebug 控制台上没有显示任何内容。
最佳答案
当您单击 remote: true
链接时,rails 不是在寻找 opportunity_modal.html.erb
,而是在寻找 opportunity_modal.js.erb
。您需要做的是将模态框放入局部,然后使用 JavaScript 渲染它。
将您的模态代码放入名为
views/deals/_opportunity_modal.html.erb
的部分。创建一个
views/deals/opportunity_modal.js.erb
文件,该文件将在触发此操作时呈现并显示模式。
$('body').append('<%= j render partial: "views/deals/opportunity_modal" %>');
$('#myModal').modal('show');
此外,您在模式中有一个变量 @opportunity
,但它没有在您的 Controller 中定义,因此请确保也定义它。
关于javascript - Rails 4 - 通过 ajax 在引导模式中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32771331/