首页 > 技术文章 > 继续ajax长轮询解决方案--递归

webSong 2017-07-23 14:16 原文

如果使用for,会有一种情况发生,就是ajax的执行会大于其他的动作的执行,那么这样的一段代码就不能实现了

for(var i=0;i<20;i++){

  console.log('你好')

  $.ajax(……)

}

怎么办呢?

递归吧,很多老程序员都是这样干的,于是,代码:

currentIndex = 0;  
function ajax(){  
    if(currentIndex>=20){   
        return;  
    }  
    var url = 'url';  
    console.log(i);  
    $.ajax({  
        type: 'get',  
        url: url,  
        dataType: "json",  
        async: false,  
        cache: true,  
        success: function(json){  
            currentIndex++;  
            console.log("test");
            ajax();  
        },  
        error: function(data){  
            console.log("error...");  
            currentIndex++;  
            ajax();  
        }  
    });  
}  

解决问题三大步:1.自己想;2.想不出来,上网去找;3.找不到,把电脑重装系统,然后递交辞职,从此告别iT。^-^

推荐阅读