javascript - 在rails中使用ajax重定向/渲染模式
问题描述
我有一个 Rails 应用程序,我需要在其中检查用户在使用特定页面时是否未通过身份验证,然后它应该在同一页面上显示登录模式,并且背景应该被淡化。
为此,我authenticate user
在应用程序控制器中调用了一种方法
def authenticated_user
if user
else
# from here I want to open a sign in modal
end
end
我目前的sessions/new
方法如下,
class SessionsController < ApplicationController
def new
respond_to do |format|
format.html
format.js
end
end
end
我在视图的会话文件夹中也有 new.js.erb,
$("#modal-window").find(".modal-content").html("<%= escape_javascript( render 'sessions/new', formats: [ :html ]) %>");
$("#modal-window").modal();
我已经尝试通过以下方式发送 ajax 请求,
redirect_to sessions_path(format: :js)
但它反而会重定向我,http://localhost:3000/reader/login.js
而不是在同一页面上打开模式。
解决方案
根据我以前的经验,这无法通过redirect_to sessions_path(format: :js)
您可以尝试以下方法:
对于 before_action
def authenticated_user
if user
else
if request.xhr?
render :authenticated_user and return
else
redirect_to request.env['HTTP_REFERER'], flash: { authenticated_user: true }
end
end
end
在布局文件中:
...
- if flash[:authenticated_user]
<%= render 'authenticated_user_modal' %>
...
认证用户.js.erb
<% html = capture do %>
<%= render 'authenticated_user_modal' %>
<% end %>
$('body').append('<%=j html %>');
$('#modal-window').modal();
# add a method that remove the modal after close it.
# $(document).on('close-modal', '#modal-window', function () {
# $('#modal-window').remove();
# });
_authenticated_user_modal.html.erb
<div id="modal-window">
...
</div>
:javascript
$('#modal-window').modal();
推荐阅读
- javascript - 在 IBM Watson IoT NodeJS 客户端上捕获错误
- css - 在移动设备中完全展开下拉菜单,但在 Wordpress 的桌面上没有
- c# - 如何获取 Class/BaseClass 的私有属性?
- docker - 使用服务创建 docker 镜像(服务发现)
- mongodb - createQueryBuilder 中的 AND 条件中的 OR 条件取决于条件
- java - 理解 JavaPairRDD.reduceByKey 函数
- javascript - 当存在多个元素时,单击一次更新值
- python - 具有多维值的 DataFrame
- android - 在 Android Studio 中选择要被自动缩进忽略的代码
- python - 特征提取 TensorFlow Estimator