问题描述
我需要使用基于 Ajax 的 post 请求传递 CSRFToken
,但不确定如何以最佳方式完成.使用在请求中内部检查 CSRFToken
的平台(仅 POST 请求)
最初我想将它添加到标题中
$(function() {$.ajaxSetup({标题:{'CSRFToken' : getCSRFTokenValue()}});});
这将使其可用于每个 Ajax 请求,但它不适用于我的情况,因为在请求中 CSRFToken
仍然为空.
有什么办法可以为所有处理POST
类型的Ajax调用设置CSRFToken
编辑如果我在 Ajax 调用中做这样的事情
data: {"newsletter-subscription-email" : "XXX" , 'CSRFToken': getCSRFTokenValue()},
一切正常.
我的问题是,我想将 CSRFToken
值作为请求参数而不是作为请求标头传递
这个怎么样,
$("body").bind("ajaxSend", function(elm, xhr, s){if (s.type == "POST") {xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());}});
参考:http://erlend.oftedal.no/blog/?blogid=118>
将CSRF
作为参数传递,
$.ajax({类型:POST",网址:文件",数据:{ CSRF:getCSRFTokenValue()}}).完成(功能(味精){alert("数据:" + msg );});
I need to pass CSRFToken
with Ajax based post request but not sure how this can done in a best way.Using a platform which internally checking CSRFToken
in request (POST request only)
initially I was thinking to add it to header like
$(function() {
$.ajaxSetup({
headers : {
'CSRFToken' : getCSRFTokenValue()
}
});
});
Which will make it available to each Ajax request, but it will not work for my case, since in request CSRFToken
is still coming as null.
Is there any way I can set CSRFToken
for all Ajax call dealing with POST
type
EditIf I do something like this in my Ajax call
data: {"newsletter-subscription-email" : "XXX" , 'CSRFToken': getCSRFTokenValue()},
Everything is working fine.
My Issue is, I want to pass CSRFToken
value as a request parameter and not as a request header
How about this,
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
}
});
Ref: http://erlend.oftedal.no/blog/?blogid=118
To pass CSRF
as parameter,
$.ajax({
type: "POST",
url: "file",
data: { CSRF: getCSRFTokenValue()}
})
.done(function( msg ) {
alert( "Data: " + msg );
});
这篇关于将 CSRFToken 添加到 Ajax 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!