javascript ajax循环请求/ 长轮询终极解决办法——递归

前端之家收集整理的这篇文章主要介绍了javascript ajax循环请求/ 长轮询终极解决办法——递归前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

ajax循环请求,不能使用for循环,原因如下:

    1. 因为ajax是异步执行,在还没有拿到服务器响应内容,就进入下一个for循环中

解决办法:递归

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

注意:

    不建议使用ajax使用同步请求,容易造成浏览器假死 


 参考:
http://www.cnblogs.com/eggTwo/p/5952955.html

http://blog.csdn.net/yuan882696yan/article/details/50296821

http://www.oschina.net/code/snippet_574558_13233

猜你在找的Ajax相关文章