且构网

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

while循环与jQuery异步AJAX调用

更新时间:2023-10-30 09:35:58

您***的选择是重组代码以使用异步当第一个完成时,ajax调用并启动下一个调用,等等。这将允许页面在图像提取之间重新显示。

Your best bet would be to restructure your code to use async ajax calls and launch the next call when the first one completes and so on. This will allow the page to redisplay between image fetches.

这也将给浏览器一个呼吸和照顾其他家务的机会,而不是认为这可能被锁定或者挂起。

This will also give the browser a chance to breathe and take care of its other housekeeping and not think that maybe it's locked up or hung.

而且,使用 async:'false'是一个坏主意。我没有理由为什么正确结构化的代码不能在这里使用异步的ajax调用,而不是在您获取这些数据时挂起浏览器。

And, use async: 'false' is a bad idea. I see no reason why properly structured code couldn't use asynchronous ajax calls here and not hang the browser while you're fetching this data.

您可以使用异步ajax这样:

You could do it with asynchronous ajax like this:

function getAllImages(position, maxImages) {
    var imgCount = 0;

    function getNextImage() {
        $.ajax({
            url: urlAJAX + 'scan=' + position,
            method: 'GET',
            async: true,
            success: function(data) {
                if (data.status == "success" && imgCount <= maxImages) {
                    ++imgCount;
                    renderImageData(data);
                    getNextImage();
                }
            }
        });
    }
    getNextImage();
}

// no while loop is needed
// just call getAllImages() and pass it the 
// position and the maxImages you want to retrieve
getAllImages('front', 20);

此外,虽然这可能看起来像递归,但它并不是真的递归,因为异步性质ajax电话。 getNextImage()在下一个调用之前已经完成,因此在技术上不会递归。

Also, while this may look like recursion, it isn't really recursion because of the async nature of the ajax call. getNextImage() has actually completed before the next one is called so it isn't technically recursion.