打破ajax响应中的循环

时间:2014-01-28 10:43:25

标签: jquery ajax for-loop break

Okey我正在为发送的消息制作进度条!我需要在ajax请求响应中打破foor循环!这是代码:

var breakFlag = false;
loop:
for (var i = 0; i < count; ++i) {
    name = userArr[i]['fName'];
    surname = userArr[i]['lName'];
    phone = userArr[i]['phone'];
    counter = i;
    $.ajax({
        type: "POST",
        url: HTTPS + '/lib/model/data/ctlSms.php?send=1',
        data: {
            smsMessage: $("#smsMessage").val(),
            smsClient: $("#smsClient").val(),
            number: $("#number").val(),
            throttle: $("#throttle").val(),
            userPhone: phone,
            fName: name,
            lName: surname,
            counter: counter
        },
        dataType: 'json',
        success: function(info) {
            if (info['results'] == "success") {
                if (start) {
                    $("#progress").width(progress);
                    $("#messageArea").append(info['info']);
                    start = false;
                } else {
                    tempPr = $("#progress").width() + progress;
                    $("#messageArea").append(info['info']);
                    $("#progress").width(tempPr);
                }
            } else {
                failed++;
                if (start) {
                    $("#progress").width(progress);
                    $("#messageArea").append(info['info']);
                    start = false;
                } else {
                    tempPr = $("#progress").width() + progress;
                    $("#messageArea").append(info['info']);
                    $("#progress").width(tempPr);
                }
            }
            if ((parseInt(info['counter'])) == count) {
                var success = count - failed;
                $("#messageArea").append("<span>Total of " + count + " messages serviced!</span><br><span style='color:green'>Sucessful: " + success + "</span><br><span style='color:red'>Failed: " + failed + "</span><br>");
            } else if (failed == $("#maxFail").val() && $("#maxFail") != "") {
                var tempCount = info['counter'] + 1;
                $("#messageArea").append("<span>Total of " + tempCount + " messages serviced!</span><br><span style='color:red'>Max failes: " + failed + " reached!</span><br>");
                breakFlag = true;
            }
        },
        error: function() {
            $("#messageArea").append("<span>Ajax error with </span><br>");
        }
    });
    console.log(breakFlag);
    if (breakFlag) {
        console.log("break");
        break loop;
    }
}

Okey所以我将全局var breakFlag设置为false,如果满足允许的最大值失败,则在ajax响应中将breakFlag设置为true,并且在循环周期结束之前,我检查此标志是否设置为true ... Okey i控制台在设置为true后显示为真,它说的是真的,但当我检查外部响应时,周期结束时它再次为假,然后xyxle开始???为什么会这样?

1 个答案:

答案 0 :(得分:0)

哦,我解决了我的问题!我没有将异步设置为false。之后,当所有东西都被冻结时,我可以将旗帜设置为真,并且在循环结束之前,它会看到它已经改变并且开始循环... :)