如何让应用程序帮助程序方法在发送的请求为 JS 格式时工作

how to have an application helper method work when the sent request is JS formatted?

本文关键字:请求 JS 格式 工作 应用程序 帮助程序 方法      更新时间:2023-09-26

我在 rails 中有一个 signed_in? 方法,如果您处于非活动状态 5 分钟,它将引导您回到登录页面。

当用户在 5 分钟后单击通过 js 提交的表单时,我该如何完成这项工作?显然,发生这种情况时,服务器会将登录页面发送回用户,但不会显示。这是我signed_in方法

def signed_in?
  unless current_user
    flash[:notice] = "Please log in"
    redirect_to root_url
  else
    if session[:expiry_time].nil? || session[:expiry_time] < 5.minutes.ago
      reset_session
      flash[:notice] = "Please log in"
      redirect_to root_url
    else
      session[:expiry_time] = 300.seconds.from_now
    end
  end
end

PS:我知道这是可怕的代码,我一定会重构它:)

但是我会首先实现一个替代重定向方法,该方法即使对于 XHR 请求也会执行完全重定向:

def redirect_with_js location
  if request.xhr?
    # HTML response is expected:
    render :text => "<script>document.location = '#{view_context.escape_javascript location}'</script>"
    # JS response is expected:
    # render :text => "document.location = '#{view_context.escape_javascript location}'"
  else
    redirect_to location
  end
end

然后在重定向时使用此方法:

redirect_with_js boomeranked_url

返回的文本取决于 AJAX 请求期望返回的响应类型(HTML 或 JS)。我已经包含了两个版本。这应该给你一些开始。

这是我想出的解决方案,我发现它更简单。在signed_in方法中:

respond_to do |format|
    format.js {
      flash[:notice] = "Please log in"
      render 'home/not_logged_in'
    }

然后在not_logged_in视图上

window.location = '<%= root_url %>';