如何防止多次ajax调用?

我正在使用以下代码通过Ajax从服务器获取内容。但是在特定情况下,我有一些完全相同的链接。在这种情况下,如何防止我的代码对同一网址进行多个服务器/ ajax调用、而替换不同的div?

jQuery('.js-ajaxfill').each(function(i){
    var _this = jQuery(this);
    jQuery.ajax({
        url: _this.data('href'),
        success: function( data ) {
            _this.children('div').replaceWith(data);
        },
        error   : function(jqXHR, textStatus, errorThrown){
            _this.html("");
        }
    });
});

Create an array to store objects with 2 properties, LinkURL and DivID. Whenever you make an ajax call, check whether that link already exist in the Array,

If it is not available : make the call,get the result, Add the entry to the Array with the corresponding the DivID.

If the item is already in the array : (that means we already made call to this url), get the DivID of that entry and get content of that Div.

You can use response caching

var ResponseCache = {};
jQuery('.js-ajaxfill').each(function(i){
    var _this = jQuery(this);
    if(!ResponseCache[_this.data('href')]){
        jQuery.ajax({
            url: _this.data('href'),
            success: function( data ) {
                 ResponseCache[_this.data('href')]=data;
                _this.children('div').replaceWith(data);
            },
            error   : function(jqXHR, textStatus, errorThrown){
                _this.html("");
            }
        });
    }else{
        _this.children('div').replaceWith(ResponseCache[_this.data('href')]);
    }
});
var ajaxfillRequests = {};

jQuery('.js-ajaxfill').each(function () {
    var _this = jQuery(this),
        url = _this.data('href');

    // make a new request only if none has been made to this URL, save the XHR
    if (!(url in ajaxfillRequests)) {
        ajaxfillRequests[url] = jQuery.get(url);
    }

    // add one set of callbacks per processed item to the XHR object
    ajaxfillRequests[url]
        .done(function (data) {
            _this.children('div').replaceWith(data);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            _this.html("");
        });
});

This works because of the way jQuery XHR objects are designed. They are promises, which means you can add as many callbacks to them as you like. It also means you can add callbacks whenever you like, it's not necessary to add callbacks in the options of the actual .ajax() call.

Once such a promise is fulfilled (i.e., the request succeeded) or rejected (i.e., the HTTP request failed) all appropriate callbacks are called.

This means you can add an individual callback for every .js-ajaxfill element you have and still make the actual request only once.