jQuery Ajax 强制刷新页面

3

我这里有一个表单,用于接收用户凭证。如果用户凭证无效,则页面不会加载,但是如果他或她拥有有效的凭证,我希望页面进行完整的刷新。我该如何实现呢?我已经尝试添加。

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

在响应的html中,但它没有起作用,看起来像是jquery正在删除脚本代码?

这里是表单提交的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());
        }
    });
})

如果用户有有效的凭据,成功响应将是这样的。
<!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>

但是页面没有重新加载。
2个回答

5
在success函数中,您可以使用JavaScript的方式重新加载:
location.reload();

一些类似于这样的东西。
$('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
        }
    });
})

那意味着当登录失败时,您的查询会出现错误,因此它不会进入成功函数。

但是如果用户输入无效,页面将重新加载。只有在用户插入有效凭据时才希望重新加载页面。 - user962206
这就是为什么我在成功函数中说的原因。 - Hugo Dozois
即使用户输入无效的凭据,成功仍将运行。它会返回不同的HTML数据。因此,无论是有效还是无效,成功仍将运行。 - user962206
1
有两种可能性。 第一种:当登录失败时,您可以抛出异常。这样Ajax请求就会回退到“error”函数。 第二种:您可以返回json或任何可解析的内容,并在接收到的data中检查登录是否成功。如果是,则location.reload(),否则执行任何操作以告知发生错误。 - Hugo Dozois

1

请尝试在成功函数中使用此代码

收到有效响应(例如1)时

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

我应该把那段代码插入到哪里?在成功函数中还是在响应的 HTML 中? - user962206
在成功函数中,检查来自php的响应后, 在php中,您可以在每次成功登录时发送1,在每次失败时发送0。 - TranQ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接