gpt4 book ai didi

javascript - 停止 AJAX 成功方法中的立即传播

转载 作者:行者123 更新时间:2023-12-01 03:12:11 27 4
gpt4 key购买 nike

这是我的代码:

$(document).on('click', '[data-submit-form]', function (event) {
var form = $(this).closest('form');

$.ajax({
url : form.attr('action'),
type : 'post',
data: form.serialize(),
async: false,
success: function (data) {
if ($.type(data) === 'object') {
alert_errors(form, data);
event.stopImmediatePropagation()
}
}
});
});

单击按钮时,这会使用 AJAX 检查服务器是否有错误。如果存在错误,则返回包含错误的对象。如果发生错误,我想阻止所单击的按钮上发生的所有其他事件。例如,该按钮还可以用于关闭模式。如果出现错误,我想阻止这种情况发生。

这根本不起作用。显示警报后,似乎 event.stopImmediatePropagation() 对按钮的其他事件没有影响。

最佳答案

这里的问题与同步或异步代码无关。

是的,如果您的 AJAX 调用是异步的,那么这将是一个问题,因为事件委托(delegate)是同步的,并且不会等待您的 AJAX 调用返回。但是您的调用是同步的,因为您设置了async: true

这里真正的根本问题是时间

您发出的 HTTP 请求——即使它是同步的,因为您设置了 async: false——需要时间才能完成,并且在完成时,浏览器的事件委托(delegate)已经发生了,因此您的 event.stopImmediatePropagation() 无效。

理想情况下,您需要将 event.stopImmediatePropagation 移动到另一个位置,如下所示:

$(document).on('click', '[data-submit-form]', function (event) {
var form = $(this).closest('form');

event.stopImmediatePropagation(); // Do it here

$.ajax({
url : form.attr('action'),
type : 'post',
data: form.serialize(),
async: false,
success: function (data) {
if ($.type(data) === 'object') {
alert_errors(form, data);
// event.stopImmediatePropagation() NOT here
}
}
});
});

编辑

您当前的方法并不是执行您想要执行的操作的最理想方法,因为您的模式关闭和表单提交逻辑耦合得太紧密,因为它们位于同一单击事件中。

您不应该使用同时关闭模式的提交表单单击事件,而应该使用单独的函数使流程更加精细:

  • 一个用于处理按钮的点击事件并提交表单
  • 一个用于关闭模态框,可以从任何地方调用

通过这种方法,您的代码可以保持原样,并在成功回调中调用 closeModal 函数,如下所示:

// By default, this will NOT close the modal anymore. You must explicitly
// call 'closeModal' where you want, e.g. in the AJAX success callback.
// This type of granularity will be much more flexible and save you headache.
$(document).on('click', '[data-submit-form]', function (event) {
var form = $(this).closest('form');

$.ajax({
url : form.attr('action'),
type : 'post',
data: form.serialize(),
async: false,
success: function (data) {
if ($.type(data) === 'object') {
alert_errors(form, data);
closeModal(); // Close modal
}
}
});
});

这样的方法更加简洁,因为随着您的功能不断增长,您将不断发现自己遇到越来越多奇怪的场景,在这些场景中您想要调用 preventDeafult stopPropagationstopImmediatePropagation 等等,我保证您将再次遇到同样的问题。这只会变得一团糟。

现在就省去麻烦。

关于javascript - 停止 AJAX 成功方法中的立即传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45759569/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com