javascript jQuery 成功,重新加载页面然后追加?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8827105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:42:05  来源:igfitidea点击:

jQuery on success, reload the page and then append?

javascriptjqueryajaxappend

提问by Drew

I have the following code:

我有以下代码:

$.ajax({
        type: 'GET',
        url: 'edit_slides.php',
        data: { user_id: user_id },
        success: function() { 
            location.reload(); 
            $('#messageContent').append('<p>success</p>'); 
        }
    });

What happens right now is that it appends and then reloads real quick so it loses the message.

现在发生的事情是它会附加然后重新加载非常快,因此它会丢失消息。

Now, I could take out the reload and it will append but in order for my changes to take affect, the page needs to be reloaded.

现在,我可以取消重新加载,它会追加,但为了让我的更改生效,需要重新加载页面。

Is there anything else I can do? I want to show a success message after reloading the page.

还有什么我可以做的吗?我想在重新加载页面后显示成功消息。

Thanks!

谢谢!

回答by jrummell

location.reload()will reload your page, which creates a new request to your server and the browser then loads the response. You could add a parameter to the query string for the message, e.g.

location.reload()将重新加载您的页面,这会向您的服务器创建一个新请求,然后浏览器加载响应。您可以在消息的查询字符串中添加一个参数,例如

$.ajax({
        type: 'GET',
        url: 'edit_slides.php',
        data: { user_id: user_id },
        success: function() { 
            window.location = "?message=success";
        }
    });

Then in server side code, you could display the message if the parameter exists. In ASP.NET MVC, it would look like this:

然后在服务器端代码中,如果参数存在,您可以显示消息。在 ASP.NET MVC 中,它看起来像这样:

@if(Request["message"] == "success")
{
    <p>success</p>
}

If you don't have server side scripting available, you can also parse the querystring with javascript.

如果您没有可用的服务器端脚本,您还可以使用 javascript 解析查询字符串

回答by ShankarSangoli

You can have some delay before you reload the page. Try this

在重新加载页面之前,您可能会有一些延迟。试试这个

$.ajax({
        type: 'GET',
        url: 'edit_slides.php',
        data: { user_id: user_id },
        success: function() { 
            $('#messageContent').append('<p>success</p>'); 
            setTimeout(function(){
               location.reload(); 
            }, 500);
        }
    });

回答by doogle

Send it to a location but with a hash in the url to indicate a success:

将它发送到一个位置,但在 url 中带有哈希值以表示成功:

$.ajax({
    type: 'GET',
    url: 'edit_slides.php',
    data: { user_id: user_id },
    success: function() { 
        window.location = window.location + "#success";
    }
});

Now when the page loads, check for the hash:

现在当页面加载时,检查哈希:

$(document).ready(function(){
    if(window.location.hash) {
        $("#messageContent").append("<p>success</p>");
    }