可以为jquery.ajaxSetup()设置范围吗?

时间:2013-05-20 12:17:30

标签: javascript ajax jquery maintainability

我正在处理大量的ajax调用,其中大部分都有相同的参数。我正在考虑使用jquery.ajaxSetup()来减少代码。

然而,jQuery并不喜欢它的API。它说:

Note: The settings specified here will affect all calls to $.ajax or AJAX-based 
derivatives such as $.get(). This can cause undesirable behavior since other callers (for 
example, plugins) may be expecting the normal default settings. For that reason we
strongly recommend against using this API. Instead, set the options explicitly in the call
or define a simple plugin to do so.

有没有办法实现这个,所以它不会触及每个js文件,包括插件?我现在没有使用与ajax一起使用的外部jQuery插件,但是如果可能的话,我想为将来的开发人员提供面向未来的证明。有可能jQuery会从它的API中删除它吗?

1 个答案:

答案 0 :(得分:3)

如何用这样的代码包装ajax()调用:

var sendAjax = function (options) {
    var type = 'GET';
    var dataType = 'json';
    var success = options.onsuccess || function () {};
    var error = options.onerror || function () {};
    var url = options.url;
    var data = options.data;
    $.ajax({
        type: type,
        url: url,
        data: data,
        dataType: dataType ,
        success: success ,
        error: error
    });
};

然后将您的ajax调用替换为sendAjax();