首页 > 解决方案 > jQuery 等到 Ajax 调用有数据再显示

问题描述

我有一个看起来像这样的 Jquery Ajax 脚本..

/* Get Values */
function get_values(id){

    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "example.com",
        "method": "GET",
        "headers": {
        "Accept": "application/json",
    },

    "dataType"   : "json",
    "mimeType": "multipart/form-data",
    }

    $.ajax(settings).done(function (response) {
        window[data_ ' + id] = response;    
    });

}


get_values(1);
get_values(2);
get_values(3);

$(".content_loader").fadeOut( function() {
    $(".main_container").html('<div class="results">' + data_1 + data_2 + data_3 +'</div>');
});

它正确地从 Ajax 调用中获取数据并将其保存到 3 个变量中......

然后它淡出微调器动画并淡出显示结果的 HTML。

我正在尝试进行设置,以便微调器和内容只有在成功获取 Ajax 调用的结果后才会淡入。

这是回调或类似的工作吗?

标签: javascriptjqueryajax

解决方案


当所有请求都完成后,返回$.ajaxPromiseget_values()并用于运行$.when()

/* Get Values */
function get_values(id) {

  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "example.com",
    "method": "GET",
    "headers": {
      "Accept": "application/json",
    },

    "dataType": "json",
    "mimeType": "multipart/form-data",
  }

  return $.ajax(settings)

}


var req1 = get_values(1),
  req2 = get_values(2),
  req3 = get_values(3);


$.when(req1, req2, req3).done(function(data_1, data_2, data_3) {
  $(".content_loader").fadeOut(function() {
    $(".main_container").html('<div class="results">' + data_1 + data_2 + data_3 + '</div>');
  });

})

推荐阅读