首页 > 解决方案 > 当值为真时需要重定向到页面

问题描述

当基于ajax调用的值为真时需要重定向到页面。问题是,如果返回 true 或 false,页面将被重定向。

<a class="btn btn-warning" onclick="return clickthis(25007); " href="test.aspx?id=eheAhgpAS38=">Start </a>
function clickthis(obj) {
  var bValid = false;

  function ajax1() {
    return $.ajax({
      type: "POST",
      url: "order.aspx/ActivateLocation",
      data: '{id:' + obj + '}',
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(r) {
        if (r.d == "1") {
          bValid = true;
        } else {
          $('#overlay').remove();
          $.growl.error({
            title: "Error",
            message: "An error occurred, Please try again."
          });
          bValid = false;
        }
      }
    });
  }

  $.when(ajax1()).done(function(a1) {
    return bValid;
  });
}

标签: jqueryajax

解决方案


首先,没有事件传递给clickthis()函数,在这方面你似乎对不显眼的事件处理程序感到困惑。另请注意,当您尝试从done()处理程序执行操作时,您无法从异步方法调用返回任何内容。window.location.assign()相反,您可以只调用$.ajax()回调。

<a class="btn btn-warning" data-id="25007" href="test.aspx?id=eheAhgpAS38=">Start </a>
$('a.btn').click(function(e) {
  e.preventDefault();

  $.ajax({
    type: "POST",
    url: "order.aspx/ActivateLocation",
    data: { id: obj },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(r) {
      $('#overlay').remove();

      if (r.d == "1") {
        window.location.assign($(this).attr('href'));
      } else {
        $.growl.error({
          title: "Error",
          message: "An error occurred, Please try again."
        });
      }
    }
  });
});

请注意,在上面的示例中,我向data. 这是将字符串连接在一起的首选做法。


推荐阅读