且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

来自等到第一个Ajax调用完成prevent第二Ajax调用

更新时间:2023-11-20 23:45:01

不幸的是所有的浏览器实现的JavaScript是单线程的,这意味着异步调用是异步的服务器,但不是同一个JavaScript和放大器;因此,等待老人的请求。你可以做什么来克服是推动在一个变量和放大器的要求;下一次检查,如果请求的状态不是200 OK /成功,不作任何进一步的要求相同的功能,样品code可以像:

  requests.push($。阿贾克斯({
        类型:'后',
        网址:进步-update.php',//基本上返回多少条记录被插入至今
        成功:函数(数据)
        {
              对于(VAR I = 0; I< requests.length;我++)
              请求[I] .abort();
        }
    }));
 

I'm running two ajax calls on page load. They both work as expected if I open the page in desktop browser.

However, if I open the same page in an android browser (Chrome for example), I noticed that the second ajax function's response is waiting for completion of the first ajax function which kinda defeats the purpose of asynchronous-ness. Both are executing concurrently, but the second function's success is only executing after completion of first ajax call's success function.

Screenshot

The fact that it is working in desktop browsers and not in android browsers leads me to believe that there must be some kind of setting in android which is blocking concurrent asynchronous calls.

If that is the case, is it possible that I can disable that? My code is as follows btw:

$(function(){           
       var intervalID = window.setInterval(function(){
                doAjax(); // this is the function which is waiting for completion of first ajax call
            }, 2000);

      // the first ajax call
      $.ajax({
    type:'post',
    url:'progress-insert.php', // basically is meant for insertion of records into db
    success:function(data)
    {
       clearInterval(intervalID);
    }   
     });

     function doAjax()
     {          
    $.ajax({
        type:'post',
        url:'progress-update.php', // basically returns how many records have been inserted so far
        success:function(data)
        {
                // do something
        }
    }); 
      }

});

Unfortunately all browsers implementation of javascript is single-threaded, which means async calls are async for servers but not for same javascript & thus wait for old request. What you can do to overcome that is to push requests in a variable & next time check if request status is not 200 Ok / Success, don't make any further call for same function, sample code can be like:

requests.push($.ajax({
        type:'post',
        url:'progress-update.php', // basically returns how many records have been inserted so far
        success:function(data)
        {
              for(var i = 0; i < requests.length; i++)
              requests[i].abort();
        }
    }));