一个While循环中的Ajax在Javascript中崩溃

时间:2017-09-27 09:01:56

标签: javascript ajax

如果支付的金额大于零,我想要一个迭代循环。但是运行代码会使浏览器崩溃。

var amount = Number($('#payment1').val());
while (amount > 0){
    $.ajax({
        type: "POST",
        url:  baseurl + "collection/getSingleAmort",
        data: {'contractid':contractID},
        success: function(result){
            var data = jQuery.parseJSON(result);
            console.log(data);
            var amortizationAmount = Number(data['amortization'][i].amortization_amount);
            amount = amount -amortizationAmount;
        },
        error: function (errorThrown){
            //toastr.error('Error!', 'Operation Done');
            //console.log(errorThrown);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

function xyz(amount){
    $.ajax({
        type: "POST",
        url:  baseurl + "collection/getSingleAmort",
        data: {'contractid':contractID},
        success: function(result){
            var data = jQuery.parseJSON(result);
            console.log(data);
            var amortizationAmount = Number(data['amortization'][i].amortization_amount);
            amount = amount -amortizationAmount;

            if(amount>0)
                xyz(amount);
        },
        error: function (errorThrown){
            //toastr.error('Error!', 'Operation Done');
            //console.log(errorThrown);
        }
    });
}

var amount = Number($('#payment1').val());
xyz(amount);

尝试这样的事情。而不是使用循环递归。

答案 1 :(得分:0)

添加async:false

var amount = Number($('#payment1').val());
while (amount > 0){
    $.ajax({
        type: "POST",
        url:  baseurl + "collection/getSingleAmort",
        data: {'contractid':contractID},
        async:false,
        success: function(result){
            var data = jQuery.parseJSON(result);
            console.log(data);
            var amortizationAmount = Number(data['amortization'][i].amortization_amount);
            amount = amount -amortizationAmount;
        },
        error: function (errorThrown){
            //toastr.error('Error!', 'Operation Done');
            //console.log(errorThrown);
        }
    });
}