jQuery $.post()的递归方式(循环)

jQuery $.post() in recursive way (loop)

本文关键字:方式 循环 递归 jQuery post      更新时间:2023-09-26

我学习jQuery,不理解这种情况:

当在调试模式下运行此代码时,所有工作正常。但是当正常运行此代码时,回调函数不启动。为什么?在非调试模式下,我有-> "Start" -> "End 10"

浏览器:Google Chrome。

var nrPost = 10;
$("#buttnX").click(function() {
    alert("Start");     
    GoPosts();
    End();
}); 
function End() {
    alert('End ' + nrPost);
};
function GoPosts() {
    $.ajaxSetup({async:false});
    var url = "http://......";
    var data = { ... };
    $.post(url, data, Callback, 'json');
};
function Callback(response) {   
    if (response.error) {
        return;
    }
    nrPost--;
    if (nrPost > 0) [
        GoPosts();
    } else {
        return;
    }
};

你有多余的};在你的代码中。我稍微改变了一下,用jQuery把它放在jsfiddle上。

http://jsfiddle.net/rH8RV/19/

它应该提醒:"开始",然后"结束10",这是正确的基于你如何写你的代码。你还期待什么吗?

我不知道你打算用你的递归实现做什么,但如果这就是全部,你实际上可以这样做:

function startLoop(nrPost) {
    // No need to put this in a loop
    $.ajaxSetup({ async: false });
    for (var i = 0; i < nrPost; i++) {
        alert('Start ' + i);
        var url = 'http://......';
        var data = {};
        $.post(url, data, function (response) {
            if (response.error)
                return;
            alert('End ' + i);
        }, 'json');
    }
}
$('#buttnX').click(function () { startLoop(10) });

希望有帮助!

我想你希望显示为:

  • "开始"
  • "End 0"

这对你的解决方案不太可能起作用。

Ajax调用$.post(url, data, Callback, 'json');是异步的。这意味着一旦$.post方法返回,请求将被发送到您提供的URL。但是,直到JQuery接收到答案后才调用Callback。立即发生的是GoPosts终止,程序继续运行。它回到代码的第5行,在单击处理程序的匿名函数中。此时,End()被调用并警告"End 10"。

你可能想把对End的调用放在Callback中:

function Callback(response)
{   
    if (response.error) 
    {
        return;
    }
    nrPost--;
    if(nrPost>0)
        GoPosts();
    else
    {
        End(); // You only want to end once you have made you nrPost calls to GoPost
        return;
    }
};