如何使循环等待到ajax响应

How to make loop wait till ajax response

本文关键字:ajax 响应 等待 何使 循环      更新时间:2023-09-26
$.ajax({
        url: "",
        data: "",
        dataType: 'json',
        success: function (data) {
            var tblBody = '';
            for(var i=0;i<data.length;i++){
                $.ajax({
                    type: "GET",
                    url: "",
                    data: {},
                    success: function(response){
                        // creating table rows
                        tblBody += rowData;
                    },
                    error: function(){
                    }
                });
            }
            $("#losssummary").append(tblBody); // appending table all rows
            createDataTable('sample_1', "M d, yyyy");
        },
        error: function(err)
        {
        }
    });
});

试试这个代码片段。

在这里,我使用了$.when().then(),然后将if替换为while

$.ajax({
        url: "",
        data: "",
        dataType: 'json',
        success: function(data) {
            var tblBody = '',
              i = 0;
            while (i < data.length) {
                $.when(
                  $.ajax({
                      type: "GET",
                      url: "",
                      data: {},
                      success: function(response) {
                          // creating table rows
                          tblBody += rowData;
                      },
                      error: function() {}
                  })
              ).then(function(data, textStatus, jqXHR) {
                  i++;
              });
            }
            $("#losssummary").append(tblBody); // appending table all rows
            createDataTable('sample_1', "M d, yyyy");
        },
        error: function(err) {}
    });
$.ajax({
        url: "",
        data: "",
        dataType: 'json',
        success: function (data) {
            var tblBody = '';
            var i = 0;
            selfCalling(data);
            function selfCalling(data){
                $.ajax({
                    type: "GET",
                    url: "",
                    data: {},
                    success: function(response){
                        // creating table rows
                        tblBody += rowData;
                        while(i<data.length){
                              selfCalling(data);
                              i++;
                        }
                    },
                    error: function(){
                    }
                });

            }
            $("#losssummary").append(tblBody); // appending table all rows
            createDataTable('sample_1', "M d, yyyy");
        },
        error: function(err)
        {
        }
    });
});

这使用递归函数来解决您的问题。希望对你有帮助

使用complete选项而不是success选项