2015-09-27 58 views
0

如何在这两个$.get调用完成后执行一些代码?

if (invoice.is(":checked")) { 
    var data = { 
     save: 1, 
     order_id: order_id 
    } 

    jQuery.get('http://domain.co.uk/customer_orders/edit/view_pdf', data, function(response) {}); 
} 

var receipt = $(this).parents(".admin_email_preview_container").find("input[name='receipt']"); 
if (receipt.is(":checked")) { 
    var data = { 
     save: 1, 
     order_id: order_id, 
     invoice: 1 
    } 

    jQuery.get('http://domain.co.uk/customer_orders/edit/view_pdf', data, function(response) {}); 
} 

我想在上述两个调用完成后才能运行另一个$.get调用。我该如何解决这个问题?

回答

1

您可以将由$.get返回的承诺存储在数组中,并将其应用于$.when()。试试这个:

var requests = []; 

if ($invoice.is(":checked")) { 
    requests.push($.get('http://domain.co.uk/customer_orders/edit/view_pdf', { 
     save: 1, 
     order_id: order_id 
    })); 
} 

var $receipt = $(this).parents(".admin_email_preview_container").find("input[name='receipt']"); 
if ($receipt.is(":checked")) { 
    requests.push($.get('http://domain.co.uk/customer_orders/edit/view_pdf', { 
     save: 1, 
     order_id: order_id, 
     invoice: 1 
    })); 
} 

$.when.apply(requests).done(function() { 
    // both $.get calls have completed, run other code here... 
    $.get('/other-endpoint'); 
}); 

注意,我稍微整理了一下代码所一贯使用的$代替jQuery(如果你需要防止$变量的污染,使用闭包),我直接移动的物体调用$.get以使其更易于阅读并删除多余的空回调函数。

+0

感谢'apply'做什么? – user892134

+0

很高兴为您提供帮助:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply –

相关问题