完成后,在另一个函数内调用JS函数

时间:2017-09-18 14:49:27

标签: javascript

我需要一些关于此代码的帮助:

$.get(function1()).done(function (){ 
    $.get(function2()).done(function (){ 
        console.log("test");                        
    });
});

当我执行此代码时,功能正常,但console.log()完成后会显示function1,但我只想在function2完成时显示。

function function1() {
    $.ajax(
        {
        type: "GET",
        url: "<?=baseURL;?>/server/null/list_user_customers",
        async: true,
        success: function(data) {

            data = $.parseJSON(data);
                // Create a deferred object
            var dfd = $.Deferred();
            dfd;
        }
    });
}
function function2() {
    $.ajax(
        {
        type: "GET",
        var url = "<?=baseURL;?>/logbook/null/reload_tickets?customer_id=" + $("#customer_select option:selected").val();
        async: true,
        success: function(data) {

            data = $.parseJSON(data);
                // Create a deferred object
            var dfd = $.Deferred();
            dfd;
        }
    });
}

2 个答案:

答案 0 :(得分:0)

使用功能2上的完整参数

      function2(){

            $.ajax({
                    url: '/Controller/Method',
                    type: 'GET',
                    complete: function () { 
                          console.log("test");
                    }
                });
      }

答案 1 :(得分:0)

您的解决方案无效,因为您的两个函数都没有返回任何内容(换句话说,它们返回undefined),因此$.get调用为空且无用。您需要做的事情如下:

// your two functions return the promises they create
function function1() {
    return $.ajax({
        // config...
    });
}
function function2() {
    return $.ajax({
        // config...
    });
}

// your main code only needs to execute those functions
// and manipulate the promises they return
function1().done(function() { 
    function2().done(function() { 
        console.log("test");
    });
});
相关问题