【问题标题】:Losing scope of click 'event' within ajax call在 ajax 调用中失去点击“事件”的范围
【发布时间】:2017-10-25 02:03:59
【问题描述】:

我需要帮助尝试根据通过 ajax 获得的数据库结果来阻止保存事件的发生。但是我似乎失去了我的“事件”变量的范围,我不知道如何保持它。非常感谢您的帮助。

基于点击保存按钮的功能:

jQuery('#saveButton').on('click',function(){
    checkForOpenActions(event)});

Ajax 调用:

function checkForOpenActions(event) {
  // determine if case has any case actions that are not resolved.
  if (jQuery('#PboCaseResolution_caseAction').val() != '') {
    jQuery.getJSON("page.request.do?page=com.blah.ajax", {
        trackingId: '$!parentId'
      },
      function(data) {
        alert("data: " + data);
        if (data == 1) {
          alert("data is 1");
          if (confirm('There are open actions on this case.  Are you sure you want to close it?')) {
            return true;
          } else {
            stopSave(event);
            return false;
          }
        }
      });
  }
}

从 Ajax 调用以停止保存:

function stopSave(event){
    alert("preventing Default");
    event.preventDefault();
}

非常感谢您的帮助!

【问题讨论】:

  • 在 ajax 完成后,您无法可靠地停止事件。 Ajax 是异步的。这意味着逻辑可以很容易地通过您所在的位置,并在 ajax 完成之前完成与该事件相关的所有逻辑,然后您尝试终止该事件。
  • 与其试图阻止事件发生,不如考虑翻转你的逻辑。始终停止保存。然后,只有当您从 ajax 获得良好响应时,才启动保存逻辑。
  • @Taplar - 我的问题是等待 Ajax 完成。我不确定如何仅在 ajax 函数返回结果后进行评估。
  • @JimBell 你把逻辑放到了 AJAX 回调函数中。因此,您调用一个执行保存的函数,而不是 return true
  • @Barmar 这就是我想做的,但是当我进入 AJAX 函数时我失去了事件的范围。

标签: jquery ajax scope click


【解决方案1】:

由于您在 AJAX 回调函数中执行确认,因此它是异步运行的,因此您不能在那里使用event.preventDefault() -- 原始事件处理程序已经返回。

您需要无条件调用event.preventDefault(),然后在用户确认后在回调函数中显式进行保存。您可以在包含按钮的表单上调用 submit() 来执行此操作。

jQuery('#saveButton').on('click', function(event) {
  checkForOpenActions(event);
});


function checkForOpenActions(event) {
  // determine if case has any case actions that are not resolved.
  if (jQuery('#PboCaseResolution_caseAction').val() != '') {
    event.preventDefault();
    jQuery.getJSON("page.request.do?page=com.blah.ajax", {
        trackingId: '$!parentId'
      },
      function(data) {
        alert("data: " + data);
        if (data == 1) {
          alert("data is 1");
          if (!confirm('There are open actions on this case.  Are you sure you want to close it?')) {
            return;
          }
        }
        event.target.form.submit();
      });
  }
}

【讨论】:

  • 谢谢@Barmar。
猜你喜欢
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多