【问题标题】:How redirect from controller side after Ajax call in Rails 6?在 Rails 6 中调用 Ajax 后如何从控制器端重定向?
【发布时间】:2020-05-25 16:41:40
【问题描述】:

我想知道是否可以从 Rails 6 中的 ajax 请求中重定向 with controller

我尝试使用

redirect_to "url"; returnrender :js => "window.location.reload" 不适合我 :(

感谢您的帮助:)

【问题讨论】:

  • 这个问题并不具体。假设您收到一个 AJAX 请求,是否要将用户重定向到另一个页面?还是要将 AJAX 请求重定向到另一个路由?如果这是关于前者,你是否已经看过How do I redirect to another webpage?

标签: ruby ajax ruby-on-rails-6


【解决方案1】:

这对我有用:

window.location.href = '/path'

例子:

$.ajax({
    url: uri,
    type: "POST",
    data: form,
    dataType: 'json',
    processData: false,
    contentType: false
}).done(function(e) {
  window.location.href = '/project_proposals'
})

【讨论】:

    【解决方案2】:

    在您的控制器中执行此操作。

    render js: "window.location='#{goal_path(@goal)}';"

    理想情况下,您希望为 Rails 应用程序尽可能多地保留 JS 中的业务逻辑。你也不能在 js 中干净地使用你的路由辅助方法。但是,您可以在控制器中设置“重定向”。

    app/view/controllers/goals/adopt_controller.rb

    # :nodoc:
    class Goals::AdoptController < ApplicationController
      def update
        # business logic....
    
        # "redirect" the client 
        render js: "window.location='#{goal_path(@goal)}';"
    
        # or make a reusable js view. this will search a wide variety of possible file names. In this case it'll match /app/view/appliation/redirect.js.erb
        # @to = goal_path(@goal)
        # render 'redirect'
    
        # the above lets rails guess what you want to do. this is a bit more explicit to only render this view is the client can accept a js response. Other scenarios will throw an error
        # @to = goal_path(@goal)
        # respond_to do |format|
        #   format.js { render 'redirect' }
        # end
      end
    end
    

    /app/view/appliation/redirect.js.erb

    window.location='<%= escape_javascript to %>';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 2013-08-08
      相关资源
      最近更新 更多