jQuery的ajaxSetup-我只想为GET请求添加默认数据 [英] jQuery's ajaxSetup - I would like to add default data for GET requests only

查看:60
本文介绍了jQuery的ajaxSetup-我只想为GET请求添加默认数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ajax驱动的网站中,我使用ajaxSetup添加了一些默认数据,如下:

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

这是为了确保在部署新修订版并且前端从后端请求html模板或json-data时出现缓存丢失.出于这个原因,后端和前端共享相同的修订号.

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.

问题在于,当前端执行PUT,POST或DELETE时,后端对于获取参数'r'有点不满意.没有办法告诉jQuery的ajax仅在执行GET请求时才使用此数据,而在执行POST,PUT或DELETE请求时则不应该使用此数据.

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.

更新:

因为我知道它,所以我首先尝试了beforeSend函数.但是可以更改settings.data,但是当beforeSend返回时,任何更改似乎都消失了.可能是我的错...:-)

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... :-)

我已经选择使用ajaxPreFilter.不过,这并不容易.options.data不是对象,而是$ .param(object)的结果,因此第一个挑战是取消参数化.我结束了:

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

推荐答案

从jQuery 1.5开始,您可以通过更优雅地处理此问题.前置过滤器:

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

这篇关于jQuery的ajaxSetup-我只想为GET请求添加默认数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆