将带有AJAX的真实性令牌发送到Rails的正确方法 [英] Proper way to send an Authenticity Token with AJAX to Rails
问题描述
此方法有效,但由于缺少真实性令牌而被停止:
This works but gets stopped because it lacks an authenticity token:
$(".ajax-referral").click(function(){
$.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script"});
return false;
});
所以我尝试像这样添加它:
So I tried adding it like so:
$(".ajax-referral").click(function(){
$.ajax({type: "POST", url: $(this).parent("form").attr("action") + "?&authenticity_token=" + AUTH_TOKEN, dataType: "script"});
return false;
});
它正确地将auth_token作为参数传递,但似乎丢失了我的其余表单.
And it passes the auth_token correctly as a param, but seems to lose the rest of my form.
无论如何完成发送有效的表单数据和真实性令牌的工作?
Anyways to accomplish both sending the form data that works, and the authenticity token as well?
这是Rails环境.而我的脑子里就有这个.
This is a rails environment. And I have this in my head.
= javascript_tag "var AUTH_TOKEN = '#{form_authenticity_token}';" if protect_against_forgery?
我尝试过的事情
1.
= hidden_field :authenticity_token, :value => form_authenticity_token
2.
$.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script", authenticity_token: AUTH_TOKEN});
3.
// Always send the authenticity_token with ajax
$(document).ajaxSend(function(event, request, settings) {
if ( settings.type != 'GET' ) {
settings.data = (settings.data ? settings.data + "&" : "")
+ "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
}
});
推荐答案
实际上,您正在阅读form的action
属性,并向其发送post ajax请求.要发送表单数据,您必须提交表单,也可以序列化表单数据并以ajax请求的形式发送,例如
Actually, you are reading the action
attribute of form and sending a post ajax request to it. to send form data you have to submit the form or you can serialize the form data and send it in ajax request like
$(".ajax-referral").click(function(){
$.ajax({
type: "POST",
url: $(this).parent("form").attr("action") + "?&authenticity_token=" + AUTH_TOKEN,
data:$(this).parent("form").serialize(),
dataType: "script"
});
return false;
});
这样做将序列化表单数据,并将其与ajax请求一起发送,并且已经通过查询字符串发送了真实性令牌
Doing this will serialize your form data and send it along with ajax request and authenticity token is already being sent via query string
这篇关于将带有AJAX的真实性令牌发送到Rails的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!