简体   繁体   English

防止多个ajax调用

[英]Prevent multiple ajax calls

I am using the following code to fetch content from server via ajax on load. 我正在使用以下代码通过加载时的ajax从服务器获取内容。 But in a particular case i have a few links that are exactly same. 但是在特定情况下,我有一些完全相同的链接。 In such case how do i prevent my code from making multiple server/ajax calls to the same url but replace different div's. 在这种情况下,如何防止我的代码对同一网址进行多个服务器/ 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 . 创建一个数组来存储具有2个属性( LinkURLDivID Whenever you make an ajax call, check whether that link already exist in the Array, 每当您进行ajax调用时,请检查Array中是否已存在该链接,

If it is not available : make the call,get the result, Add the entry to the Array with the corresponding the DivID . 如果不可用,请执行以下操作 :调用,获取结果,将条目添加到具有相应DivID的Array中。

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. 如果该项已经在数组中 :(这意味着我们已经调用了该URL),请获取DivID目的DivID并获取该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. 这是由于jQuery XHR对象的设计方式而起作用的。 They are promises , which means you can add as many callbacks to them as you like. 它们是promises ,这意味着您可以根据需要添加尽可能多的回调。 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. 这也意味着您可以随时添加回调,而不必在实际.ajax()调用的选项中添加回调。

Once such a promise is fulfilled (ie, the request succeeded) or rejected (ie, the HTTP request failed) all appropriate callbacks are called. 一旦实现了这样的承诺(即请求成功)或被拒绝(即HTTP请求失败),就会调用所有适当的回调。

This means you can add an individual callback for every .js-ajaxfill element you have and still make the actual request only once. 这意味着您可以为每个拥有的.js-ajaxfill元素添加一个单独的回调,并且仍然仅实际发出一次请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM