可以为jquery.ajaxSetup()设置作用域吗?

Can a scope be set for jquery.ajaxSetup()?

本文关键字:设置 作用域 jquery ajaxSetup      更新时间:2023-09-26

我正在处理一些有大量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中删除这个?

如何用这样的代码包装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();