第二个 Jquery json 在第一个 Jquery 完成之前被解雇

Second Jquery json getting fired before first Jquery being complete

我有两个 javascript 函数,它们使用 jquery json 填充一些数据。两者都工作正常但问题是第二个函数在第一个函数执行之前被调用。我的代码是:

$(document).ready(function () {        
    loadSubject();
    getTopic();       
});

function loadSubject() {
    var CourseId = document.getElementById('CourseId').value;
    alert('22222');
    jQuery.support.cors = true;
    $.ajax({
        url: 'http://220.45.89.129/api/LibraryApi',
        type: 'Get',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
        dataType: 'json',
        success: function (data) {
            var subjectDivs = "";
            var divs = "";
            var i = 1;
            $.each(data, function (index, value) {
                divs = "";
                // Some code here
                i = i + 1;
            });
            subjectDivs = subjectDivs + divs;
            alert('11111');
            $('#cCount').val(i);
            document.getElementById('accordion').innerHTML = subjectDivs;
        },
        error: function (e) {
            alert(JSON.stringify(e));
        }
    });
}

function getTopic() {
    var c = $('#cCount').val();
    alert(c);
    for (var i = 1; i <= c; i++) {
        var subId = $('#hdn_' + i).val();
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://220.45.89.129/api/LibraryApi',
            type: 'Get',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: { DataType: 'Topic', UserRecId: 0, ParentId: subId },
            dataType: 'json',
            success: function (data) {
                var topicDivs = "";
                var divs = "";
                tDivs = '';
                $.each(data, function (index, value) {
                    divs = '';
                    divs = '<div class="row">';
                    divs = divs + '<div class="subject">' + value.Name + '</div>';
                    divs = divs + "</div>";
                    topicDivs = topicDivs + divs;
                });
                $('#sDiv_' + i).html(topicDivs);
            },
            error: function (e) {
                alert(JSON.stringify(e));
            }
        });
    }
}

从第一个调用第二个函数ajax success function

$(document).ready(function () {        
    loadSubject();
});

    function loadSubject() {
        // code here
        $.ajax({
            url: 'http://220.45.89.129/api/LibraryApi',
            type: 'Get',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
            dataType: 'json',
            success: function (data) {
               //code here
                   getTopic();    // Second function calling
            },
            error: function (e) {
                alert(JSON.stringify(e));
            }
        });
    }

现在,当第一个函数执行成功后,将调用第二个函数。

这不是 ajax get 的执行方式。如果你一个接一个地放置两个 jquery ajax 请求,那么它们将按顺序执行,第二个请求不必在第一个请求完成或收到第一个请求的响应后执行。

如果您希望发生这种情况,有两种方法

1.使用异步:'false'

这会请求等到收到响应后再执行 javascript 中的下一条语句。

What does "async: false" do in jQuery.ajax()?

2。使用回调

编写您希望在第一个 ajax 请求成功或完成回调时执行的第二个函数。

jQuery ajax success callback function definition

尝试添加 return statement before $.ajax({}) within both loadSubject and getTopic , to return jQuery promise object , which can be handled at deferred.then

    function loadSubject() {
      return $.ajax()
    }

    function getTopic() {
      return $.ajax()
    }

    loadSubject().then(getTopic);

function a() {
  return new $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(1) 
    }, 2000)
  }).promise().then(function(data) {
    console.log(data)
  })
}

function b() {
  return new $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(2) 
    }, 2000)
  }).promise().then(function(data) {
    console.log(data)
  })
}

a().then(b)

您必须在第一个 ajax 请求中添加 async:false,它会停止下一次执行,直到第一个 ajax 请求完成执行。 所以你的第一个函数是这样的

function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
jQuery.support.cors = true;
$.ajax({
    url: 'http://220.45.89.129/api/LibraryApi',
    type: 'Get',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
    dataType: 'json',
    async:false,
    success: function (data) {
        var subjectDivs = "";
        var divs = "";
        var i = 1;
        $.each(data, function (index, value) {
            divs = "";
            // Some code here
            i = i + 1;
        });
        subjectDivs = subjectDivs + divs;
        alert('11111');
        $('#cCount').val(i);
        document.getElementById('accordion').innerHTML = subjectDivs;
    },
    error: function (e) {
        alert(JSON.stringify(e));
    }
});

}