Ajax在重定向上显示消息

时间:2017-04-27 14:58:24

标签: jquery ajax toastr

在我的ajax调用中,如果成功,我想重定向到另一个URL并显示由toastr形成的消息。

这是我的ajax:

var redirectUrl = '@Url.Action("Index", "Informations")';

bootbox.confirm({
    title: "Delete?",
    message: "Are you sure you want to delete this?",
    buttons: {
        cancel: {
            label: '<i class="fa fa-times"></i> Cancel'
        },
        confirm: {
            label: '<i class="fa fa-check"></i> Confirm'
        }
    },
    callback: function(result) {
        if (result) {
            toastr.options = {
                timeOut: 5000
            }

            $.ajax({
                url: "/api/Informations/" + btn.attr("data-id"),
                method: "DELETE",
                success: function () {
                    window.location.href = redirectUrl;
                    toastr.success("Successfully deleted");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    var status = capitalizeFirstLetter(textStatus);

                    toastr.error(status + " - " + errorThrown, "Sorry, something went wrong.");
                 }
             });
         }
      }
  });

现在问题肯定是调用toastr.success方法之前的重定向..那么如何在新页面上显示成功消息?

1 个答案:

答案 0 :(得分:2)

您可以使用toastr提供的回调,可能是onclickonHidden

toastr.options.onShown      = function() { window.location.href = redirectUrl; }
toastr.options.onHidden     = function() { window.location.href = redirectUrl; }
toastr.options.onclick      = function() { window.location.href = redirectUrl; }
toastr.options.onCloseClick = function() { window.location.href = redirectUrl; }

一个例子:

$('.hej').click(function(e) {
  e.preventDefault();
  toastr.options.onHidden = function() { console.log('I\'m hidden'); }
  toastr.options.onclick = function() { console.log('You clicked me'); }
  toastr.success('Have fun storming the castle!', 'Miracle Max Says');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://codeseven.github.io/toastr/build/toastr.min.js"></script>
<link href="http://codeseven.github.io/toastr/build/toastr.min.css" rel="stylesheet"/>

<a href="#" class="hej">Click me!</a>

在你的情况下,它可能是这样的:

<script>
  ...
  $.ajax({
    url: "/api/Informations/" + btn.attr("data-id"),
    method: "DELETE",
    success: function () {
      toastr.options.onHidden = function() { window.location.href = redirectUrl; }
      toastr.success("Successfully deleted");
    },
    error: function(jqXHR, textStatus, errorThrown) {
      var status = capitalizeFirstLetter(textStatus);
      toastr.error(status + " - " + errorThrown, "Sorry, something went wrong.");
     }
  });
  ...
</script>

已更新:如果你想要的是在你重定向的新页面中显示一条消息,那么你可以通过url将该消息作为参数传递:

toastr.options.onHidden = function() { window.location.href = redirectUrl + '?message=any_message'; }

我已经意识到必须在toastr.success分配之前设置选项。