如何正确配置jquery .done方法



我有一个通过AJAX填充列表框的函数。

function listCourses() {    
var s= document.getElementById( 'courses' );
return $.ajax({
    type: "GET",
    url: "http://localhost:80/RickVideos/courseLib.xml",
    dataType: "xml",
    success: function( xml ){
        // load array with course codes
        var arr = [];
        $(xml).find( 'courseCode' ).each(function() {
                s.options[ s.options.length ] = new Option( $( this ).text());
        });
     },
    error: function() {
        alert("An error occurred while processing XML file." );
    }
});

当函数被调用时,我希望在AJAX处理发生时显示一个模态对话框,然后将模态对话框替换为显示填充列表框的另一个模态对话框。

 $(  "#ajaxLoading #listOfCurrentProjects" ).overlay({
    left: "center",
    top: "center", 
   closeOnClick: false, 
    load: false
}); 
$( "#newCourse" ).click( function() { 
   $("#ajaxLoading").overlay().load();
    listCourses().done(function() {
        $("#ajaxLoading").overlay().close();
        $("#listOfCurrentProjects").overlay().load();   
});;

点击newCourse按钮,显示ajaxLoading对话框,然后关闭。不显示"listOfCurrentProjects"对话框。当第二次点击newCourse按钮时,ajaxLoading对话框显示,然后被listOfCurrentProjects对话框取代。这是期望的行为。为什么它不发生在最初的按钮点击?

使用在jQuery 1.5以后实现的承诺,比如.done()。您可以解析不使用successerror回调。

var listCourses = function() { 
    return $.ajax({
        type: "GET",
        url: "http://localhost:80/RickVideos/courseLib.xml",
        dataType: "xml"
    });
});

您可以随时调用AJAX,使用listCourses()。您甚至可以将其绑定到处理程序,就像您所做的那样:

$('#newCourse').click(function() { 
    $('#ajaxLoading').overlay().load();
    listCourses().done(function(xml) {
        var s = document.getElementById('courses');
        $(xml).find( 'courseCode' ).each(function() {
            s.options[s.options.length] = new Option($( this ).text());
        });
        $("#ajaxLoading").overlay().close();
        $("#listOfCurrentProjects").overlay().load();
    }).error(function() {
        alert("An error occurred while processing XML file." );
    });
});

您可以使它更详细,通过一个变量进行AJAX调用:

var listCourses = $.ajax({
    type: "GET",
    url: "http://localhost:80/RickVideos/courseLib.xml",
    dataType: "xml"
});

然后在监听#newCourse上的click事件时,简单地引用变量listCourses,而不是函数listCourse(s):

$('#newCourse').click(function() { 
    $('#ajaxLoading').overlay().load();
    listCourses.done(function(xml) {
        var s = document.getElementById('courses');
        $(xml).find( 'courseCode' ).each(function() {
            s.options[s.options.length] = new Option($( this ).text());
        });
        $("#ajaxLoading").overlay().close();
        $("#listOfCurrentProjects").overlay().load();
    }).error(function() {
        alert("An error occurred while processing XML file." );
    });
});

最新更新