Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - Adding CSRFToken to Ajax request

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

Edit If 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

question from:https://stackoverflow.com/questions/22063612/adding-csrftoken-to-ajax-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 );
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...