我使用两个 AJAX GET 请求从两个不同的来源获取数据。
在每个请求中,我解析响应数据,创建一个包含每个项目相关数据的临时数组,然后将此临时数组插入主数组。
但是,这仅在我在 AJAX 请求中包含 "async: false"
时有效,该请求现已弃用。
有没有其他方法可以编写这段代码? (注意:虽然我在此代码片段中使用了两个 AJAX 请求,但在我正在处理的项目中我可能总共需要使用四个请求)。
function get_results() {
$(document).ready(function() {
var master_array = [];
$.ajax({
type: "GET",
url: "http//:www.source1.com",
dataType: "xml",
async: false,
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]);
});
}
});
$.ajax({
type: "GET",
url: "http//:www.source2.com",
dataType: "xml",
async: false,
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]);
});
}
});
});
}
最佳答案
您可以使用 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);
});
}
关于javascript - 连续 AJAX 调用的 "async: false"替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658172/