Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

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

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

var revision = '159';
$.ajaxSetup({
    dataType: "text json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
        r: revision
    }
});

This is to ensure cache-miss when a new revision is deployed and the frontend ask for html templates or json-data from the backend. The backend and frontend share the same revision number for this reason.

The problem is that the backend it somewhat unhappy about getting the parameter 'r' when the frontend does a PUT, POST or DELETE. Is there no way to tell jQuery's ajax that this data should only be used when doing GET requests and not when doing POST, PUT or DELETE requests.

UPDATE:

I tried the beforeSend function first, since I knew it. However changing settings.data was possible, but any change seemed to vanish when beforeSend returned. It may have been my fault... :-)

I have settled on the ajaxPreFilter instead. It was not easy as pie though. The options.data is not an object, but the result of $.param(object), so the first challenge was to un-parameterize it. I ended up with this:

var revision = '159';
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    // do not send data for POST/PUT/DELETE
    if (originalOptions.type !== 'GET' || options.type !== 'GET') {
        return;
    }

    var data = originalOptions.data;
    if (originalOptions.data !== undefined) {
        if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
            data = $.deparam(originalOptions.data); // see http://benalman.com/code/projects/jquery-bbq/examples/deparam/
        }
    } else {
        data = {};
    }

    options.data = $.param($.extend(data, { r: revision }));
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...