【问题标题】:JQuery Ajax Force Page refreshJQuery Ajax 强制页面刷新
【发布时间】:2013-01-18 01:47:41
【问题描述】:

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

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>

但页面没有重新加载。

【问题讨论】:

    标签: javascript jquery ajax html refresh


    【解决方案1】:

    在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
            }
        });
    })
    

    这意味着您的查询会在登录失败时引发错误,因此它不会进入您的成功函数。

    【讨论】:

    • 但是如果用户输入无效页面将重新加载。如果用户插入了有效的凭据,只希望页面重新加载
    • 这就是我在成功函数中说的原因
    • 即使用户插入无效凭据,成功仍然会运行。它返回不同的 HTML 数据。所以无论是无效还是无效,成功仍然会运行
    • 嗯,有两种可能性。首先:登录失败时抛出异常。使 Ajax 请求回退到“错误”函数。第二:您返回 json 或任何可以解析的内容,然后签入data您收到它,登录成功。如果是,location.reload()else 做任何事情来告诉你有错误
    【解决方案2】:

    看看能否在成功函数中使用这段代码

    收到有效响应(如 1)

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

    【讨论】:

    • 我应该在哪里插入该代码?在成功函数里面?还是在已经响应的html中?
    • 在检查来自 php 的响应后的成功函数中,在 php 中,您可以在每次成功登录时设置 1,在每次登录失败时设置 0。
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2021-10-28
    • 1970-01-01
    • 2014-10-06
    • 2011-09-16
    • 2018-06-19
    相关资源
    最近更新 更多