Adding a general parameter to all ajax calls made with jQuery

后端 未结 4 1094
离开以前
离开以前 2021-01-11 09:19

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 ch

相关标签:
4条回答
  • 2021-01-11 09:41

    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);
        } 
    });
    
    0 讨论(0)
  • 2021-01-11 09:44

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

    0 讨论(0)
  • 2021-01-11 09:48

    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.

    0 讨论(0)
  • 2021-01-11 09:49

    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 讨论(0)
提交回复
热议问题