Jquery 2.1 -等待两个ajax调用结束,然后销毁元素
Jquery 2.1 - wait for the two ajax calls to end and then destroy element
我的函数中有两个ajax调用。当两个ajax调用完成后,。popup-loading需要删除。我该怎么做呢?
功能:
// Create login/create user panel
function createPopupUser() {
var
body = $('body'),
baseUrl = body.data('base-url'),
// start of user panel
userPanel = '<div class="popup-container">';
userPanel += '<div class="popup-loading">';
userPanel += '</div>';
userPanel += '<div class="popup-panel">';
userPanel += '<div class="popup-new-user">';
userPanel += '</div>';
userPanel += '<div class="popup-login">';
userPanel += '</div>';
userPanel += '</div>';
userPanel += '</div>';
// end of user panel
$('body').prepend(userPanel);
var newUserResponse, loginResponse;
$.ajax({ type: "GET",
url: baseUrl + 'users/create',
async: false,
success : function(text)
{
newUserResponse = text;
}
});
$.ajax({ type: "GET",
url: baseUrl + 'users/login',
async: false,
success : function(text)
{
loginResponse = text;
}
});
var popup = $('body').find('.popup-container');
$( document ).ajaxComplete(function() { popup.find('.popup-loading').remove(); });
popup.find('.popup-new-user').append(newUserResponse);
popup.find('.popup-login').append(loginResponse);
}
使用Deferred
:
$def1 = $.ajax({...});
$def2 = $.ajax({...});
// Do stuff
$.when($def1, $def2).done(function() {
// Remove loading indicator
});
使用promise,特别是$.when
方法来同步两者:
var ajax1 = $.ajax(...)
var ajax2 = $.ajax(...)
$.when(ajax1, ajax2).done(function() {
popup.find('.popup-loading').remove();
})
注。失去async: false
选项!如今,它被认为是不好的做法,而且在任何情况下(没有双关语的意思),它与使用承诺是不兼容的。
相关文章:
- 在另一个函数成功结束后调用该函数
- 在动画结束之前调用函数
- settimeout调用的函数未结束
- 函数1结束后,JavaScript调用函数2
- Javascript渲染.如何编写Javascript;t在函数调用结束之前继续执行代码
- 在源节点上调用 stop() 是否会触发已结束的事件
- 在 html5 视频结束时调用 AngularJS 控制器函数
- addclass循环结束时调用函数
- 调用并结束ajax函数
- Ionic Angular/为什么在控制器功能结束之前不调用服务
- 无法从响应的结束事件中对 Http.Request 进行递归调用
- Ajax 调用返回语法错误:输入意外结束
- 在转换结束时调用回调
- jQuery函数使用包含setTimeout的每个循环调用自身,立即发生,而不是在结束时发生
- 如何在间隔结束后调用函数
- 如何在调用它的函数结束时执行回调
- 如何在js中等待http调用结束
- 第一个事件结束后调用一个事件
- 等待JS函数中异步调用的结束.(jQuery.Deferred?)
- 如何在媒体结束时调用函数,该函数从javascript文件中播放