Rails Ajax无法validationCSRF令牌真实性

在我的rails应用程序中,我在ajax的ajaxpost上收到“警告:无法validationCSRF令牌真实性”。

app / views / layouts / application.html.haml

!!! %html %head = stylesheet_link_tag "application", :media => "all" = javascript_include_tag "application" = csrf_meta_tags %body = yield 

ajaxpost

 $.ajax({ url: '#{card_credits_path}', type: 'POST', beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')}, dataType: "json", data: { credit_uri: response.data.uri, email: $('#email:hidden').val(), name: $('.name').val() }, success: function(randomobject) { window.location = '/'; }, error: function(){ console.log("Card information is wrong!"); } }); 

假设您已使用Rails csrf_meta_tag标记设置CSRF令牌,请求的令牌将在csrf-token元标记中可用:

  

由于您使用的是jQuery,因此可以通过为beforeSend键调用以下值来将令牌传递给AJAX请求:

 function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))} 

这段代码已经存在于rails/jquery-ujs ,因此使用它代码要容易rails/jquery-ujs

  beforeSend: $.rails.CSRFProtection