【问题标题】:ajax success redirect not working [duplicate]ajax成功重定向不起作用[重复]
【发布时间】:2017-05-11 12:15:00
【问题描述】:

我的表单中有一个 ajax 帖子。当它成功时,我想重定向到另一个网页..

我现在拥有的:

$.ajax({
        type : 'POST',
        url : '/system/login.php',
        data : formData,
        dataType : 'json',

    success: function(data) {
        if(!data.success){
            if(data.errors.username){
                alert(data.errors.username);
            }

            if(data.errors.password){
                alert(data.errors.password);
            }
            if(data.errors.login){
                alert(data.errors.login);
            }
        }
        else{
            location.href = "http://localhost/me.php"
        }
    },
    error: function(xhr){
     alert(xhr.responseText);
  }
});

有人可以帮助我吗?因为我没有尝试过任何工作。

【问题讨论】:

  • 在 DUP 答案中具体查看 this comment
  • 会触发错误功能吗?因为 system/login.php 可能不会返回 200 OK

标签: php jquery ajax


【解决方案1】:

改变这一行

location.href = "http://localhost/me.php"

到

window.location.href='http://localhost/me.php'

确保 ajax 响应正常

【讨论】:

    【解决方案2】:

    jQuery 不是必需的,window.location.replace(...) 将最好地模拟 HTTP 重定向。

    window.location.replace(...) 比使用 window.location.href 更好,因为 replace() 不会将原始页面保留在会话历史记录中,这意味着用户不会陷入永不-结束后退按钮惨败。

    如果要模拟某人点击链接,请使用 location.href

    如果要模拟 HTTP 重定向,请使用 location.replace

    例如:

    // similar behavior as an HTTP redirect
    window.location.replace("http://localhost/me.php");
    
    // similar behavior as clicking on a link
    window.location.href = "http://localhost/me.php";
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多