簡體   English   中英

將redirect_to格式更改為:Rails中的js

[英]Change redirect_to format to :js in Rails

我有一個控制器操作,只有登錄的用戶才能訪問。如果用戶沒有登錄,我想將它們重定向到登錄表單,這是一個由ajax驅動的燈箱。 雖然初始請求是html格式,但我需要更改為js 現在,我正在嘗試這樣:

def new
  if user_signed_in?
    @company = Company.new
  else
    redirect_to new_user_session_path, format: 'js'
  end
end

不幸的是,它仍然將重定向視為html格式。 有沒有辦法讓重定向被視為js

我在rails 3.2.13中嘗試過這是有效的,我希望它可以解決

if user_signed_in?
  .....
else
  if request.xhr?
    flash[:notice] = "Please login."
    flash.keep(:notice)
    render :js => "window.location = #{new_user_session_path}"
  else
    .....
  end
end

我想你可能正在尋找一個respond_to塊以及前面提到的過濾器:

class CompaniesController < ApplicationController
  before_filter :login

  def new 
    @company = Company.new

    render json: @company, layout: false # layout false if you do not want rails to render a page of json
  end

  private

  def login
    if !user_signed_in?
     #your login code here
    end
  end
end

不要忘記將您的dataType ajax選項設置為json:

$.ajax({
    url: "company/new" //your rails url, what is there is just my best guess
    data: query, //whatever paramaters you have
    dataType: "json", // or html, whichever you desire
    type: "GET",
    success: function (data) {
        //your code here
    }
 });

對於任何人來到這個並使用Rails 5我做了這個,這在youractionname.js.erb文件中工作,如果在一個想要重定向時在控制器youractionname函數內設置@redirect變量。

# ruby control flow
<% if @redirect != nil %>
  // javascript call to use rails variable as redirect destination.
  location.replace("<%=@redirect%>");
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM