我将jquery ujs用于ajax请求(data-remote="true"
(。我的问题是,第一个请求是可以的,当第二个请求正在运行时,它会中断。每当我调用事件$('#modal').empty()
、$('#modal').text('')
或$('#modal').html('')
时,将不再调用任何事件。
需要明确的是,这是代码:
$(document).on('ajax:beforeSend', function () {
console.log('beforeSend');
$('#modal').empty().modal('show');
});
$(document).on('ajax:send', function () {
console.log('send');
});
$(document).on('ajax:success', function (e, xhr) {
console.log('success');
$('#modal').html(xhr).drags({ handle: '.modal-header' }).modal('show');
if (typeof doWork === 'function') {
doWork();
}
});
$(document).on('ajax:complete', function () {
console.log('complete');
});
控制台输出:
- 发送前
- 发送
- 成功
- 完成
- 发送前
如果我将$('#modal').empty().modal('show');
移动到send事件,那么它将被调用,但成功方法再也不会被调用(两个错误都不完整,仅此而已(。
这个问题让我烦恼了好几个小时。。。谢谢你的帮助。
如何将empty()
移动到ajax:complete
?在这种情况下,当您的模态关闭时,它将为下一次使用打开,并准备好重用。我建议你把这个命令放在最后一步,这样它就不会引起任何问题。如下所示:$(document).on('ajax:complete', function () { console.log('complete'); . . . . $('#modal').empty(); });
我认为这不是最好的解决方案,肯定还有其他解决方案。但我希望这个解决方案能解决你的问题。
$('#modal').on('hidden.bs.modal', function () {
$(this).empty()
})
我的解决方法是避免使用jquery ujs事件和使用全局ajax事件,所以我的最终工作代码是:
$(document).ajaxSend(function () {
$('#modal').empty().modal('show');
});
$(document).ajaxSuccess(function (e, xhr) {
$('#modal').html(xhr.responseText).drags({ handle: '.modal-header' }).modal('show');
if (typeof doWork === 'function') {
doWork();
}
});