重定向到成功后阿贾克斯形式重定向、形式、后阿贾克斯

2023-09-10 16:38:51 作者:Mr.***

我有一个形式与远程=>真。 而现在我的控制器是这样的:

I've got a form with remote => true. And right now my controller looks like:

  # POST /items
  # POST /items.json
  def create
    @item = @store.items.build(params[:item])

    respond_to do |format|
      if @item.save
        format.html { redirect_to edit_admin_item_path(@item), :flash => {:success => "#{@item.name} was successfully created."} }
        format.js { render :js => "window.location.href = ('#{edit_admin_item_path(@item)}');"}
        format.json { render json: @item, status: :created, location: @item }
      else
        format.html { render action: "new" }
        format.js { render :partial => 'fail_create.js.erb', :locals => { :ajax_errors => @item.errors.full_messages } }
        format.json { render json: @item.errors, status: :unprocessable_entity }       
      end
    end
  end

这工作,但感觉很笨拙。它也不会允许我使用闪光灯的通知,这是伤心的时候确实如此。

Which works but feels very clumsy. It also doesn't allow me to use a flash notice, which is sad time indeed.

在理想情况下我觉得我应该可以简单地用format.js {redirect_to时...}或者对证的请求头和redirect_to时。Sheesh!

Ideally I feel like I should be able to simply use "format.js { redirect_to...} or check against the request headers and redirect_to. Sheesh!

我不知道什么是最好的解决办法是。任何意见将是超级真棒,谢谢提前!

I'm not sure what the best solution is. Any advice would be super awesome, thanks in advance!

- PS - 我知道这已被要求有点过,但都无济于事:How一个成功的AJAX表单提交后重定向。似乎有很多问题相似左右浮动,但没有真正的解决方案。

-- PS -- I know this has been asked somewhat before but to no avail: How to redirect after a successful AJAX form submission. There seems to many questions similar floating around, but no real solutions.

推荐答案

我想这可能是不可能的。一个Ajax请求的响应由XMLHtt prequest处理。如果一个3XX响应返回,XMLHtt prequest将遵循重定向本身,如果URL是同一产地。不管你如何设置的标头,浏览器无法意识到这一点。所以唯一的办法可以改变window.location会用一些JavaScript。

I think it might be impossible. The response to a Ajax request is processed by XMLHttpRequest. If a 3xx response is returned, XMLHttpRequest will follow the redirect itself, if the URL is of same origin. No matter how you set the headers, the browser cannot be aware of that. So the only way could be changing window.location with some Javascript.