Javascript 在rails中使用ajax重定向/渲染模式
我有一个rails应用程序,在其中我需要检查用户在使用特定页面时是否未经过身份验证,然后它应该在同一页面上显示登录模式,并且背景应该褪色 为此,我在应用程序控制器中有一个名为Javascript 在rails中使用ajax重定向/渲染模式,javascript,ruby-on-rails,ruby,ajax,Javascript,Ruby On Rails,Ruby,Ajax,我有一个rails应用程序,在其中我需要检查用户在使用特定页面时是否未经过身份验证,然后它应该在同一页面上显示登录模式,并且背景应该褪色 为此,我在应用程序控制器中有一个名为authenticate user的方法 def authenticated_user if user else # from here I want to open a sign in modal end end 我当前的会话/新的方法如下: class SessionsController < Appl
authenticate user
的方法
def authenticated_user
if user
else
# from here I want to open a sign in modal
end
end
我当前的会话/新的方法如下:
class SessionsController < ApplicationController
def new
respond_to do |format|
format.html
format.js
end
end
end
redirect_to sessions_path(format: :js)
但它也会重定向我http://localhost:3000/reader/login.js
而不是在同一页面上打开模式。根据我以前的经验,这无法通过重定向到会话路径(format::js)
您可以尝试以下方法:
在行动之前
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' %>
...
。。。
-如果闪存[:已验证的用户]
...
已验证的_user.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();
# });
$('body')。追加('');
$(“#模态窗口”).modal();
#添加一个方法,在关闭模态后将其删除。
#$(文档).on('close-modal','#modal window',函数(){
#$(“#模式窗口”).remove();
# });
_已验证的\u用户\u modal.html.erb
<div id="modal-window">
...
</div>
:javascript
$('#modal-window').modal();
...
:javascript
$(“#模态窗口”).modal();
根据我以前的经验,您不能使用重定向到会话路径(format::js)来实现这一点。我可以问一下,认证用户的请求是ajax还是html?认证用户是我在过滤任何请求之前调用的方法(在我的情况下,它只是html请求)。
<div id="modal-window">
...
</div>
:javascript
$('#modal-window').modal();