设计根据 AJAX 请求注销用户。轨道3.1
我有一个使用 AJAX 进行 CRUD 的控制器,但是每当我单击远程链接之一(例如删除)时,我都会看到 Rails 服务器已决定将我注销并重定向我。检查服务器日志表明它无法验证 CSRF 真实性。如何在我的请求中包含 CSRF 令牌?
跑步: - 轨道 3.1 - 设计1.4.4 - jquery-rails 1.0.13
相关控制器操作:
def destroy
@article = Article.find(params[:id])
if @article.destroy
flash[:notice] = "Article deleted."
respond_to do |format|
format.html{redirect_to articles_path}
format.js{}
end
else
flash[:error] = "Try Again."
redirect_to :back
end
Layouts/application.html.erb
<head>
<title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-1.1.1.min.css>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag :defaults %>
<script type="text/javascript">jQuery.ajaxSetup({ beforeSend: function (xhr) { xhr.setRequestHeader("Accept", "text/javascript"); } });</script>
<%= csrf_meta_tag %>
<%= yield(:head) %>
</head>
提前致谢。
I have a controller which uses AJAX for CRUD, however whenever I click on one of my remote links (Delete for example) I see the rails server has decided to log me out and redirect me. Inspection of the server logs state that it cannot verify CSRF Authenticity. How do I include the CSRF token in my request?
Running:
- Rails 3.1
- Devise 1.4.4
- jquery-rails 1.0.13
Relevant Controller Action:
def destroy
@article = Article.find(params[:id])
if @article.destroy
flash[:notice] = "Article deleted."
respond_to do |format|
format.html{redirect_to articles_path}
format.js{}
end
else
flash[:error] = "Try Again."
redirect_to :back
end
Layouts/application.html.erb
<head>
<title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-1.1.1.min.css>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag :defaults %>
<script type="text/javascript">jQuery.ajaxSetup({ beforeSend: function (xhr) { xhr.setRequestHeader("Accept", "text/javascript"); } });</script>
<%= csrf_meta_tag %>
<%= yield(:head) %>
</head>
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rails 3.1 使用 gem 'jquery-rails',它希望您在 application.js 文件中包含此内容:
我忘记了 jquery_ujs 并且遇到了与您相同的问题。
Rails 3.1 uses the gem 'jquery-rails', which wants you to have this in your application.js file:
I had forgotten the jquery_ujs and was getting the same problem as you.
你应该在你的 html 页面中包含这个:
它会生成以下内容:
每当你执行 POST(DELETE、PUT 实际上是 POST,但 _method 独立设置)时,你应该包含
{authenticity_token: "the token comes here"}
在您发布的数据中。You should have this in your html page:
which generates the following:
Whenever you do POST (DELETE, PUT are actually POST but with _method set dependently), you should get include the
{authenticity_token: "the token comes here"}
in the data your post together with.