javascript JQuery Ajax 强制页面刷新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14668481/
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 22:17:22  来源:igfitidea点击:

JQuery Ajax Force Page refresh

javascriptjqueryajaxhtmlrefresh

提问by user962206

I have here a form where that accepts user credentials. if the user has invalid user credentials the page will not load however if he or she has valid credentials I want the page to do full page refresh how would I achieve that? I have tried adding.

我在这里有一个接受用户凭据的表单。如果用户的用户凭据无效,页面将不会加载,但是如果他或她拥有有效的凭据,我希望页面进行整页刷新,我将如何实现?我试过添加。

window.location.href = window.location.href; 

On the response html but it did not work, it seems like jquery is removing the script code?

在响应 html 但它不起作用,似乎 jquery 正在删除脚本代码?

here's the AJAX for form submission.

这是用于表单提交的 AJAX。

$('body').on('submit', '#sign-in', function(e) {
    e.preventDefault();

    var data = $(this).serialize();

    var url = $(this).attr('action');
    $.ajax({
        //this is the php file that processes the data and send mail
        url : url,
        type : "POST",
        data : data,
        //Do not cache the page
        cache : false,
        //success
        success : function(data) {
            alert(data);
            $('#loginModal').html($(data).find('#loginModal').html());
        }
    });
})

if the user has valid credentials the response from the success would be this

如果用户具有有效凭据,则成功的响应将是这样

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
    window.location.href = window.location.href;

</script>
</head>

but the page is not reloading.

但页面没有重新加载。

回答by Hugo Dozois

In the success function you can use the JavaScript way to reload :

在成功函数中,您可以使用 JavaScript 方式重新加载:

location.reload();

A bit like this

有点像这样

$('body').on('submit', '#sign-in', function(e) {
    e.preventDefault();

    var data = $(this).serialize();

    var url = $(this).attr('action');
    $.ajax({
        //this is the php file that processes the data and send mail
        url : url,
        type : "POST",
        data : data,
        //Do not cache the page
        cache : false,
        //login success
        success : function(data) {
            //... your other code
            location.reload(); //reload the page on the success
        }
    });
})

That implies that your query thorws an error when the login fails so it doesn't go in your success function.

这意味着您的查询在登录失败时会引发错误,因此它不会出现在您的成功功能中。

回答by TranQ

See if you can use this code in the successfunction

看看是否可以在成功函数中使用此代码

On receiving valid response (like 1)

收到有效响应时(如 1)

$(document).attr('location').href='your location'