And*_*res 4 ajax jquery ruby-on-rails authenticity-token
由于几个原因,我需要通过Ajax向控制器发送一个post请求,我不能涉及一个表单,它必须是在资源> javascript或标签之间的文件中编写的JS Ajax请求.
我写了一个似乎正确传递数据的函数.但是,它没有传递有效的真实性令牌,因此不允许请求通过.
有没有办法遵守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',
});
};
Run Code Online (Sandbox Code Playgroud)
此表格通过以下参数
{"utf8"=>"?", "_method"=>"patch", "open_ender"=>
{"answer_id"=>"4",
"content"=>"<p>testing text</p>"},
"id"=>"5"}
Run Code Online (Sandbox Code Playgroud)
我已经尝试在Ajax对象中包含以下行
authenticity_token: $('meta[name=csrf-token]').attr('content'),
Run Code Online (Sandbox Code Playgroud)
这在应用程序布局中没有成功
$(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }
});
});
Run Code Online (Sandbox Code Playgroud)
UPDATE
公寓来自Aniket的解决方案.添加
authenticity_token: true
Run Code Online (Sandbox Code Playgroud)
在表单选项哈希也解决了这个问题
只需在表单内部传递一个带有真实性令牌值的隐藏字段即可.
<%= f.hidden_field :authenticity_token, value: form_authenticity_token %>
Run Code Online (Sandbox Code Playgroud)
要么
<input type=hidden name="authenticity_token" value="<%= form_authenticity_token %>">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5466 次 |
| 最近记录: |