开发者

Adding a general parameter to all ajax calls made with jQuery

I'm using AJAX to load data from the server as needed. I'开发者_如何学编程m currently working on updating the server software to the latest version. One of the things I noticed that has changed is that every request now requires me to pass along a token. This means I have to add a new parameter to every request. I'm hoping to achieve this by a general method, without having to modify every single AJAX call.

Any pointers?


You could use the $.ajaxSetup method as illustrated in the following article.


What you're looking for is a Prefilter, here's a sample from the page:

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
  // Modify options, control originalOptions, store jqXHR, etc
});

This requires JQuery 1.5.


An example using ajaxPrefilter to extend posted data :

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if (originalOptions.type === 'POST' || options.type === 'POST') {
        var modifiedData = $.extend({},originalOptions.context.options.data,{ property:"val",property_two: "val" });
        options.context.options.data = modifiedData;
        options.data = $.param(modifiedData,true);
    } 
});


I took Raja Khoury's solution, but edited it a bit since context was null in my case.

This is what I came up with:

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        if (originalOptions.type === 'POST' || options.type === 'POST') {
            var modifiedData = $.extend({}, originalOptions.data, { __RequestVerificationToken: getAntiForgeryToken() });
            options.data = $.param(modifiedData);
        }
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜