【问题标题】:How to do an action after an AJAX call is done? [duplicate]AJAX 调用完成后如何执行操作? [复制]
【发布时间】:2016-12-21 04:59:59
【问题描述】:

我尝试在不同的地方调用一个函数。这就是为什么我返回真或假。 我遇到的问题是在 hasCreditCard 有时间之前打电话,直接去 else...

if (hasCreditCard($('#memberId').val())) {
  ...
}
else{
  ...
}

function hasCreditCard(memberId) {
    var url = getHostName() + "/members/" + memberId + "/creditcard";
    jQuery.ajax({
        type: "head",
        url: url,
        contentType: "application/json",
        headers: {
            "Authorization": "Basic " + $.cookie('authorization')
        },
        success: function (data, status, jqXHR) {
            if (jqXHR.status == 200) {
                return true;
            }
            return false;
        },
        error: function (jqXHR, status) {
            return false;
        }
    });
}

【问题讨论】:

  • 把你的代码放在ajax success`` function which you want to execute in if`条件下,在ajax error函数里把你想要执行的代码放在else部分
  • 你可以试试 async: ajax 的 false 属性

标签: javascript jquery ajax if-statement callback


【解决方案1】:

因为 AJAX 调用是 asynchronous,而您的 if-statement 不会等待调用结束。

两种解决方案:

#1您可以将回调传递给函数并在成功/错误处理程序中调用此回调:

getCreditCard($('#memberId').val(), function (hasCreditCard) {
  if (hasCreditCard) {
    ...
  } else {
    ...
  }
})

function getCreditCard(memberId, nextStep) {
  ...
  jQuery.ajax({
    ...
    success: function (data, status, jqXHR) {
      if (jqXHR.status == 200) {
        nextStep(true)
        return
      }
      nextStep(false)
    },
    error: function (jqXHR, status) {
      nextStep(false)
    }
  })
}

#2您可以创建另一个全局函数并在成功/错误处理程序中调用此函数:

getCreditCard($('#memberId').val())

function getCreditCard(memberId) {
  ...
  jQuery.ajax({
    ...
    success: function (data, status, jqXHR) {
      if (jqXHR.status == 200) {
        nextStep(true)
        return
      }
      nextStep(false)
    },
    error: function (jqXHR, status) {
      nextStep(false)
    }
  })
}

function nextStep(hasCreditCard) {
  if (hasCreditCard) {
    ...
  } else {
    ...
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2020-01-31
    • 2014-06-10
    • 1970-01-01
    • 2019-05-17
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多