我正在尝试使用 $.when 来执行我的 Ajax 请求并在执行后操作数据。这是我到目前为止的代码:
function method2 (data2) {
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp',
success: function(data2){
console.log(data2);
}
});
}
function method3 (){
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp',
success: function(data3){
console.log(data3);
}
});
}
function method4(){
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp',
success: function(data4){
console.log(data4);
}
});
}
function method5(){
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp',
success: function(data5){
console.log(data5);
}
});
}
function method6(){
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp',
success: function(data6){
console.log(data6);
}
});
}
// Execute all needed data from all of the requests.
function showData(){
}
$.when( method1(), method2(), method3(), method4(), method5(), method6() ).then( showData() );
所以我想在我的 HTML 页面上显示来自这些 Ajax get 请求的数据,并且我想执行函数 showData() 内的所有代码,但问题是当我尝试在 showData() 中使用 console.log() 它们,我想知道如何访问它们?有什么解决方案或想法吗?
最佳答案
来自documentation稍作修改:
function method1() {
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp'
});
}
function method2() {
return $.ajax({
type: 'GET',
url: 'Some URL',
dataType: 'jsonp'
});
}
// Execute all needed data from all of the requests.
function showData(v1, v2) {
console.log(v1);
console.log(v2);
}
$.when(method1, method2).done(showData);
关于javascript - 通过 Promise 创建并执行多个 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35670272/