javascript - 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 个变量中......
- 数据_1
- 数据_2
- 数据_3
然后它淡出微调器动画并淡出显示结果的 HTML。
我正在尝试进行设置,以便微调器和内容只有在成功获取 Ajax 调用的结果后才会淡入。
这是回调或类似的工作吗?
解决方案
当所有请求都完成后,返回$.ajax
Promiseget_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>');
});
})
推荐阅读
- javascript - 连接完成后承诺不解决
- vue.js - 如何在列表项上使用 v-model 来设置对象的值
- comparator - 尝试打开 indexedDB 数据库,我收到此错误:无效参数:idb_cmp1 与现有比较器不匹配:leveldb.BytewiseComparator'
- javascript - 在 `vue-cli` 中转译传播运算符以支持 MS Edge
- android - 如何在同一个 Android 应用中使用 Firestore 数据库和数据存储
- algorithm - 为什么这个算法的时间是 O(n^2) 而不是 O(n^3)?
- xml - XSD 架构错误:XmlSchema 错误:元素 http://www.w3.org/2001/XMLSchema:element 在此上下文中无效
- java - “onBindViewHolder”函数中的Android Recycler View问题“无法从非静态方法调用静态方法”
- java - 变异器和构造器?
- android - 如何从布尔资源中获取可绘制资源