设计根据AJAX请求注销用户.Rails 3.1



我有一个使用AJAX进行CRUD的控制器,但是每当我单击我的一个远程链接(例如Delete)时,我看到rails服务器已经决定注销我并重定向我。对服务器日志的检查表明无法验证CSRF真实性。如何在请求中包含CSRF令牌?

运行:- Rails 3.1—设计1.4.4jquery-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

布局/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>

Rails 3.1使用gem 'jquery-rails',它希望您在application.js文件中包含此内容:

//= require jquery
//= require jquery_ujs

我忘记了jquery_ujs,遇到了和你一样的问题。

你应该在你的html页面:

<%= csrf_meta_tag %>

生成以下内容:

<meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="the token comes here"/>

每当你做POST (DELETE, PUT实际上是POST,但与_method设置依赖),你应该得到包括{authenticity_token: "the token comes here"}在你的数据与。

最新更新