【问题标题】:Is it possible to use redirect_to when it's called by remote ajax?远程ajax调用时是否可以使用redirect_to?
【发布时间】:2013-04-18 22:03:54
【问题描述】:

现在此控制器中的此操作由远程 ajax 调用调用。
仅当复选框[:call] 被选中并提交时,
我想让它重定向到 ......_path 与 flash 消息。

有可能吗?如果可能,怎么做?

控制器

.....
if params[:comment][:call] == "1"
    flash[:notice] = "you checked and submit!"
    redirect_to ....._path
else
    ajax page reload
end

查看表单(使用 ajax 远程)

<%=form_for(([@community, @comment]), :remote => true, :class => 'form' ) do |f| %>
    <%= f.check_box :call, :label => 'call' %> call
        <div class="form-actions">
            <div class="input-append">
                <%= f.text_field :body, :id => "input", :class => "box" %>  
            <button type="submit" class="btn">submit</button>
        </div>
    </div>
<% end %>

评论模型

attr_accessible :icon, :call
....
def call
    @call ||= "0"
end

def call=(value)
    @call = value
end

【问题讨论】:

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


    【解决方案1】:

    你将不得不用 js 而不是控制器来编写这段代码。

    在控制器中:

    def action_name
      ....
      respond_to do |format|
        format.js
      end
    end
    

    制作一个 action_name.js.erb 文件并编写以下代码:

    <% if params[:comment][:call] == "1" %>
      <% flash[:notice] = "you checked and submit!" %>
      window.location.href = <%= some_url %>
    <% else %>
      $("#some_div_id").html("something")    //ajax page reload
    <% end %>
    

    希望这对你有用。

    【讨论】:

    • 非常感谢。这是我想要的完美答案:)
    【解决方案2】:

    不,这是不可能的。

    您必须渲染将更改窗口位置的 javascript:

    window.location.href = 'http://your new location';
    

    当然,在您的 js 视图中,您可以通过以下方式为 url 使用动态值:

    window.location.href = '<%= @a_controller_variable %>';
    

    【讨论】:

      猜你喜欢
      • 2010-12-07
      • 2013-04-26
      • 1970-01-01
      • 2013-11-11
      • 2011-12-08
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多