简体   繁体   English

使用jQuery在页面刷新之前显示消息

[英]Showing message before page refresh using jQuery

I want to display ajax result message before page refresh, but something is wrong. 我想在页面刷新之前显示ajax结果消息,但是出了点问题。 My code is like this: 我的代码是这样的:

$.ajax({
    cache: false,
    type: "POST",
    url: "@(Url.RouteUrl("DummyRequest"))",
    success: function (data) {
        if (data.Success) {
            $('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
            setInterval(function () {
                location.reload();
            }, 5000);
        }
        else {
            $('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
            /*setInterval(function () {
                location.reload();
            }, 5000);*/
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        $('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
    }
});

My code is working just fine on else situation. 我的代码在其他情况下工作正常。 When I tried, message appears, then after 5 secs page reloads itself. 当我尝试时,会显示消息,然后在5秒后页面重新加载。 But when if situation is on, page reloads itself, however message doesn't show. 但是,当如果情况是,页面重新加载本身,但是信息不显示。

How can I solve this problem? 我怎么解决这个问题?

Try something like this: 尝试这样的事情:

$('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow", function () {
    setTimeout(function () {
        location.reload();
    }, 5000);
});

The difference is that the setTimeout() will not be called until after the fadeOut() is finished executing. 不同之处在于,在fadeOut()执行完毕之后才会调用setTimeout()

Its depends on response time of server.. so if response from server is late then not working correctly.. so you have to wait for AJAX response then you have to display popup and redirect. 它取决于服务器的响应时间..所以如果来自服务器的响应迟到然后不能正常工作..所以你必须等待AJAX​​响应然后你必须显示弹出和重定向。 so use ajax option async: false in your ajax request. 所以在你的ajax请求中使用ajax选项async: false as mentioned below 如下所述

$.ajax({
    cache: false,
    async: false,
    type: "POST",
    url: "@(Url.RouteUrl("DummyRequest"))",
    success: function (data) {
        if (data.Success) {
            $('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
            setInterval(function () {
                location.reload();
            }, 5000);
        }
        else {
            $('#dummy-notification').text(data.Result).fadeIn("slow").delay(3000).fadeOut("slow");
            /*setInterval(function () {
                location.reload();
            }, 5000);*/
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        $('#dummy-notification').text("Something went wrong.").fadeIn("slow").delay(3000).fadeOut("slow");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM