javascript - 通过 Promise 创建并执行多个 Ajax 请求

标签 javascript jquery ajax get

我正在尝试使用 $.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/

相关文章:

javascript 函数总是返回 false

javascript - 使用 jquery 在 div 周围创建边框

jQuery UI 问题 : why do the elements go flying around the screen?

php - Uploadify-操作完成,但未进行上传

Ajax 与 Socket.io

ajax - 如何获得XPATH动态变化的AJAX元素

javascript - 您可以在 OS X 上安装用 JavaScript 编写的 Office 应用程序加载项吗

javascript - 将网页中的npapi插件对象从一个div移动到另一个div,为什么插件会销毁并重新创建?[chrome,FireFox]

javascript - 通过端口与 Elm 进行外部 Firebase 通信?

javascript - jQuery 选择器中的通配符