这看起来很奇怪。我有一个链接,我想对 Controller 进行 ajax 调用以删除用户的响应,然后重定向到另一个页面。这是链接的代码:
<%= link_to 'try again', reset_score_path, remote: true, controller: "pages",
action: "reset_score", class: "btn btn-primary tryAgain", data: { confirm: 'This
will reset your score to <strong>zero</strong> and reset all of your answers so you
can start fresh. Do you want to continue?', commit: "Restart", cancel: "No Thanks",
focus: 'none'}, title: "Try Again?" %>
这是 Controller 操作:
def reset_score
current_user.responses.destroy_all
current_user.certificate.destroy
redirect_to action: "course_page1", format: "html" and return
end
但问题是浏览器中没有任何反应;它不会重定向。但控制台显示它正在处理和渲染 View 。查看控制台输出:
Started GET "/pages/reset_score" for 127.0.0.1 at 2014-10-17 07:19:45 -0500
Processing by PagesController#reset_score as JS
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 62 ORDER BY "users"."id" ASC LIMIT 1
Response Load (0.3ms) SELECT "responses".* FROM "responses" WHERE "responses"."user_id" = ? [["user_id", 62]]
[AWS S3 404 0.306706 0 retries] head_object(:bucket_name=>"...",:key=>"x.pdf") AWS::S3::Errors::NoSuchKey No Such Key
Redirected to http://localhost:3000/pages/course_page1.html
Completed 302 Found in 315ms (ActiveRecord: 0.6ms)
Started GET "/pages/course_page1.html" for 127.0.0.1 at 2014-10-17 07:19:45 -0500
Processing by PagesController#course_page1 as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 62 ORDER BY "users"."id" ASC LIMIT 1
Rendered pages/course_page1.html.erb within layouts/application (0.3ms)
Rendered layouts/_header.html.erb (0.4ms)
Completed 200 OK in 80ms (Views: 78.5ms | ActiveRecord: 0.2ms)
所以它似乎表明 View 已渲染。然而,浏览器实际上并不显示此 View - 它只是停留在上一页上。
有什么想法吗?我被难住了!
(是的,我知道 AWS 给出了错误,但我假设它与此问题无关?)
编辑: 感谢 Pamio 的回答,这是 Controller 的解决方案代码(替换上面的第 4 行):
def reset_score
current_user.responses.destroy_all
current_user.certificate.destroy
respond_to do |format|
format.js { render :js => "window.location.href = '#{pages_course_page1_path}'" }
end
end
最佳答案
您使用了redirect_to操作:“course_page1”,格式:“html”并返回
,这是不正确的。如果是 html 请求而不是 ajax,重定向将正常工作。因此,如果您想重定向,尽管请求是 ajax,请使用类似这样的内容
format.js { render :js => "window.location.href = '#{course_page_path}'"}
或者从链接中删除 remote: true
属性,这样它就可以正常工作了。
希望有帮助
关于javascript - Rails 控制台显示 View 已渲染,但在浏览器中未渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425083/