您可以使用JQuery $.promise对象来实现此目的
当你return $.ajax它实际上有一些内置方法,例如
$.done()和$.when。
在您的场景中,您希望在第一个Ajax请求完成后执行Ajax函数。
因此,我们将创建两个变量来表示代码中的两个Ajax请求
就像我之前提到的,当你返回Ajax请求时,你实际上可以将它用作$.promise对象并享受它带来的优势,例如$.done()函数。
function get_results() {
$(document).ready(function() {
var master_array = [];
var MyFirstFunction = function() {
return $.ajax({
type: "GET",
url: "http//:www.source1.com",
dataType: "xml",
success: function(xml) {
$(xml).find('product').each(function() {
var Average = $(this).find('Average').text();
var Price = $(this).find('Price').text();
var Name = $(this).find('Name').text();
var Url = $(this).find('Url').text();
var Image = $(this).find('Image').text();
master_array.push([Average, Price, Name, Url, Image]);
});
}
});
};
var MySecondFunction = function(){
return $.ajax({
type: "GET",
url: "http//:www.source2.com",
dataType: "xml",
success: function(xml) {
$(xml).find('product').each(function() {
var Average = $(this).find('Average').text();
var Price = $(this).find('Price').text();
var Name = $(this).find('Name').text();
var Url = $(this).find('Url').text();
var Image = $(this).find('Image').text();
master_array.push([Average, Price, Name, Url, Image]);
});
}
});
};
//We use it after the assignment of the variables because if would have put it before them we would got undefined, you can read more about it here:[Hoisting][4].
MyFirstFunction().done(MySecondFunction);
});
}