jQuery's ajaxSetup - I would like to add default data for GET requests only

前端 未结 2 1806
暗喜
暗喜 2020-12-09 15:55

In a ajax-driven site I have added some default data using the ajaxSetup, ala this:

var revision = \'159\';
$.ajaxSetup({
    dataType: \"text json\",
    co         


        
相关标签:
2条回答
  • 2020-12-09 16:39

    Starting jQuery 1.5, you can handle this much more elegantly via Prefilters:

    var revision = '159';
    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        // do not send data for POST/PUT/DELETE
        if(originalOptions.type !== 'GET' || options.type !== 'GET') {
            return;
        }
    
        options.data = $.extend(originalOptions.data, { r: revision });
    });
    
    0 讨论(0)
  • 2020-12-09 16:54

    I think what you might be able to use is beforeSend.

    var revision = '159';
    $.ajaxSetup({
        dataType: "json",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        beforeSend: function(jqXHR, settings) {
            if(settings.type == "GET")
                settings.data = $.extend(settings.data, { ... });
            return true;
        }
    });
    

    jqXHR documentation

    BeforeSend documentation as well as your settings available

    I coded this blind, so I hope it gets you going in the right direction.

    0 讨论(0)
提交回复
热议问题