Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax overwrite data/url beforeSend on specific url

Question

I wanna set a ajax setting for global ajax handled by jQuery

Condition:

If ajax url is 'www.example.com', the data (querystring or body) will append token.


I tried two method

.ajaxPrefilter

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {

    // Add data to ajax option
    if (options.url.match(/www\.example\.com/i) !== null) {
        originalOptions.data.token = 'i_am_token'
    }

});

To add token when url is www.example.com-> it not work!

In console/debugger originalOptions Object is added token property, but request sent not having token parameter

.ajaxSetup / beforeSend Event

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {

        // Only GET Method
        if (settings.url.match(/www\.example\.com/i) == null){
            settings.url.replace(/((\.\/[a-z][0-9])*\?+[=%&a-z0-9]*)&?token=[a-z0-9]*&?([=%&a-z0-9]*)/gi, "$1$3")
        }

    },
    data: {
        token: 'i_am_token'
    }
});

And a reverse resolution, add token for each ajax request.

Same as last one, settings.url changed by string replace in the console/debugger. But request still sent original url.


Test in jsfiddle: http://jsfiddle.net/qVLN2/2/

Thanks for your reading and help :)

like image 626
Chia-Yu Pai Avatar asked Jul 25 '13 03:07

Chia-Yu Pai


Video Answer


1 Answers

You should notice that the String.replace function doesn't affect the original string!

You can try using settings.url = settings.url.replace(....); in your code.

like image 68
alexcasalboni Avatar answered Oct 17 '22 09:10

alexcasalboni