在Rails中使用Twitter Bootstrap jQuery模态框链接到另一个页面

3

我希望这个模态框能够弹出并显示另一个页面的内容,但由于我刚接触Jquery,无法使其正常工作。是否有一种方法可以修改下面的代码,以便在模态框中弹出“/contact/”页面的内容?

----------
# this content is on http://myurl.com/contact/
 <div style="display: none;" id="myModal" class="modal hide fade">
 <p>this is my email app here...</p>
</div>
----------
# this is the button on a 'show' page where i want someone to push to bring up the contents of the above page in the modal.
<a data-toggle="modal" href="#myModal" class="btn btn-primary btn-large">Launch Email</a>

@amitamb - 不,我还没有尝试过IFrame,但我在搜索中看到了一些解决方案,所以我认为我会先尝试它,因为它似乎最容易。 - Tim
1个回答

7

好的,这里的关键是,“其他页面”可能是Rails控制器动作的结果,该控制器通常会在单独的URL上呈现页面,对吗?但是Bootstrap假设当您单击链接时,其HTML已经存在于当前页面上。

那么如何处理呢?您需要通过AJAX进行控制器请求(link_to ... :remote => true是一个不错的起点),并更改控制器以将其内容添加到当前页面的某个div中。完成后,您上面的代码或类似于它的代码(或类似于Bootstrap页面上记录的内容)将实现您想要的效果。

编辑:添加具体示例,在我的情况下,在Bootstrap模态框中打开编辑用户页面(使用Devise gem进行身份验证):

app/views/devise/registrations/_edit.html.erb:

<div class="modal hide fade in" id="user-edit">
  <div class="modal-header">
    <button class="close" data-dismiss="modal">x</button>
    <h2>Edit User</h2>
  </div>

  <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:method => :put}) do |f| %>
    <div class="modal-body">
      <%= devise_error_messages! %>

      <div>
        <%= f.label :name %><br/>
        <%= f.text_field :name %>
      </div>

      <div>
         <%= f.label :email %><br/>
        <%= f.email_field :email %>
      </div>

      <div>
        <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br/>
        <%= f.password_field :password, :autocomplete => "off" %>
      </div>

      <div>
        <%= f.label :password_confirmation %><br/>
        <%= f.password_field :password_confirmation %>
      </div>

      <div>
        <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br/>
        <%= f.password_field :current_password %>
      </div>
    </div>

    <div class="modal-footer">
      <%= f.button "Update", :class => "btn btn-primary", :data => { :dismiss => "modal"} %>
      <a href="#" class="btn" data-dismiss="modal">Close</a>
    </div>
  <% end %>
</div>

app/views/devise/registrations/edit.js.erb:

$("#main").before("<%= escape_javascript(render "edit", :formats => [:html]) %>");
$("#user-edit").modal();

还有一个链接可以从任何页面调用它(我现在将其放在导航中:

<li><%= link_to "Edit Account", edit_user_registration_path, :remote => true %></li>

你说得对 - 这是一个电子邮件表单,就像联系我们页面一样,我想在模态框中呈现它。我只想允许用户通过表单在其页面上给另一个用户发送电子邮件。感谢您提交此内容,但不幸的是我是个新手,不知道该如何实现。我已经使用了 :remote => true,但是关于“更改控制器以使其内容添加到 div”我不确定你的意思是什么。 - Tim
有没有人有一个逐步的例子来说明这是如何工作的? :) - Tim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接