Load a bulk of Json file and send Json data with Ajax one by one

fmchanprogrammingLeave a Comment

var ajaxManager = (function() {
     var requests = [];

     return {
        addReq:  function(opt) {
            requests.push(opt);
        },
        removeReq:  function(opt) {
            if( $.inArray(opt, requests) > -1 )
                requests.splice($.inArray(opt, requests), 1);
        },
        run: function() {
            var self = this,
                oriSuc;

            if( requests.length ) {
                oriSuc = requests[0].complete;

                requests[0].complete = function() {
                     if( typeof(oriSuc) === 'function' ) oriSuc();
                     requests.shift();
                     self.run.apply(self, []);
                };   

                $.ajax(requests[0]);
            } else {
              self.tid = setTimeout(function() {
                 self.run.apply(self, []);
              }, 1000);
            }
        },
        stop:  function() {
            requests = [];
            clearTimeout(this.tid);
        }
     };
}());

reference: https://stackoverflow.com/questions/4785724/queue-ajax-requests-using-jquery-queue

$(function(){
  ajaxManager.run();
  $("div").each(function(){
    var obj = $(this);
    var jqxhr = $.getJSON( "posts/"+$(this).text(), function(data) {
       ajaxManager.addReq({
            type: 'POST',
            url: 'https://abc/posts/',
            beforeSend: function (xhr) {
              xhr.setRequestHeader('Authorization', 'Bearer <?php echo $_GET['access_token']; ?>');
            },
            data: JSON.stringify(data),
            dataType: 'json',
            contentType : 'application/json',
            success: function (response) { console.log(response); obj.remove(); },
            error: function (xhr, ajaxOptions, thrownError) { 
              console.log(xhr.status);
              console.error(thrownError);
            },
       });
    });
  });
});

There are some json file names on the page

<div>a.json</div>
<div>b.json</div>

Leave a Reply

Your email address will not be published. Required fields are marked *