试图了解jquery.done()的工作原理

时间:2016-07-27 13:45:41

标签: javascript jquery

我有一组级联选项下拉框,我试图通过javascript和amp; jQuery的。在$(document).ready部分中,我正在尝试实现jquery .done()函数,以确保在下一次运行开始运行之前完成每个先前的函数,但它似乎没有工作:

$(document).ready(function () {
    $.when(getSchoolYears()).done(function () {
        $.when(getDistricts()).done(function () {
            $.when(getAreas()).done(function () {
                $.when(getSchoolTypes()).done(function () {
                    $.when(getSchoolLevels()).done(function () {
                        $.when(getGrades()).done(function () {
                            $.when(getEvents()).done(function () {
                                $.when(getResolutions()).done(function () {
                                    $.when(getSchools()).done(function () {
                                        loadCharts();
                                    })
                                })
                            })
                        })
                    })
                })
            })
        })
    })
})

专注于前两个功能,getSchoolYears()& getDistricts(),我把consle.log语句放到这些函数中,并在getSchoolYears()消息之前记录getDistricts()的消息

function getSchoolYears() {
    var data = [];
    var param = {};

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=UTF-8",
        url: "../WebServices/myLocations.asmx/get_SchoolYears",
        data: JSON.stringify(param),
        dataType: "json",
        success: function (msg) {
            var data = [];

            data.push(msg.d);

            $('#ddSchoolYear li').remove();

            for (var i = 0; i <= data.length; i++) {
                $('#ddSchoolYear').append(data[i]);
            }

            $('#hidSchoolYear').val(ddSubmitted('#ddSchoolYear input', '#lblYear'));
            console.log('finished');
        }
    });
}

function getDistricts() {
    console.log($('#hidSchoolYear').val());
    var param = { "endYear": $('#hidSchoolYear').val() };

    return $.ajax({
        type: "POST",
        contentType: "application/json; charset=UTF-8",
        url: "../WebServices/myLocations.asmx/get_Districts",
        data: JSON.stringify(param),
        dataType: "json",
        success: function (msg) {
            var data = [];

            data.push(msg.d);

            $('#ddDistrict li').remove();

            for (var i = 0; i <= data.length; i++) {
                $('#ddDistrict').append(data[i]);
            }
        }
    });
}

我不明白.done()函数是如何工作的?有没有办法确保一个函数在下一个函数开始之前完成?

0 个答案:

没有答案