Rails 如何在不涉及表单的情况下在 Ajax 请求中发送真实性令牌?

Rails How to send an Authenticity Token in an Ajax Request without a form involved?

出于多种原因,我需要通过 Ajax 向控制器发送 post 请求,但我无法通过表单来完成,它必须是 JS Ajax在 assets > javascript 或标签之间写入文件内的请求。

我写了一个似乎可以正确传递数据的函数。但是,它没有传递有效的真实性令牌,因此不允许请求通过。

有没有办法遵守 CSRF 保护生成令牌以便控制器满意?

到目前为止我的Ajax函数是:

  var functionOne = function() {
  var $form = $('#'  + tinyMCE.activeEditor.formElement.id);
  var action = $form.attr('action')
  $.ajax({
    method: "POST",
    url: action,
    data: $form.serialize(),
    dataType: 'script',
  });
};

此表单正在传递以下参数

{"utf8"=>"✓", "_method"=>"patch", "open_ender"=>
  {"answer_id"=>"4",
  "content"=>"<p>testing text</p>"},
  "id"=>"5"}

我尝试在 Ajax 对象中包含以下行

authenticity_token: $('meta[name=csrf-token]').attr('content'),

这在应用程序布局头部没有成功

$(function(){
  $.ajaxSetup({
  headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }
  });
});

更新

Appart 来自 Aniket 的解决方案。添加

authenticity_token: true 

表单选项哈希也解决了这个问题

只需在您的表单中传递一个具有真实性令牌值的隐藏字段,这应该会起作用。

<%= f.hidden_field :authenticity_token, value: form_authenticity_token %>

<input type=hidden name="authenticity_token" value="<%= form_authenticity_token %>">
Use the below:

  var functionOne = function() {
  var $form = $('#'  + tinyMCE.activeEditor.formElement.id);
  $form = $form.append('<input type = hidden name = "authenticity_token" value = "<%= form_authenticity_token %>">')
  var action = $form.attr('action')
  $.ajax({
    method: "POST",
    url: action,
    data: $form.serialize(),
    dataType: 'script',
  });
};