How to redirect after a successful AJAX form submission (Rails 3.2)

China☆狼群 提交于 2019-12-10 10:27:30

问题


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?



来源:https://stackoverflow.com/questions/9506445/how-to-redirect-after-a-successful-ajax-form-submission-rails-3-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!