How to redirect after a successful AJAX form submi

2019-05-16 16:22发布

问题:

Suppose you have an edit form with :remote => true. Your controller method looks like

 def update
    @article = Article.find(params[:id])

    respond_to do |format|
        if @article.update_attributes(params[:article])
            format.html { redirect_to @article}
            format.js { render :js => "window.location.replace('#{article_path(@article)}');"}
        else
            format.html { render :action => "edit" }
            # Render update.js.erb which replaces the body of the form
            format.js {}
        end
    end
end

What's the best way to do the redirect on successful article update in Rails 3.2.1? The raw JS solution seems a little sleazy, but I do like the fact that it's obvious that it's performing the same function as the format.html version.

I would prefer a solution that does not use RJS (if that even works in Rails 3.2?)

回答1:

How about adding the below line of code on the view file itself

#some_file.js.erb

`window.location = redirect_path

As you mentioned in the question you do not prefer RJS, but I think it's better to follow this pattern better than writing the js code in the controller.



回答2:

Does your ajax interact with a model (.php,.asp?). My preferred method in this instance is to create a success/fail criteria within the model after submission and redirect directly from there. Not sure if that makes sense in this application though?