php - 从 PHP 调用 Jquery AJAX 后强制重定向

标签 php jquery http-redirect

我有一个自定义框架,我在我的Request 文件中检测请求是否为ajax。在我的基本 Controller 中,我检查用户是否登录:

If user is not logged in:
  1. if request is ajax - force JS redirect from PHP (unable to do)
  2. if request is not ajax - PHP redirect (header, works)

我无法让编号 1 工作。

这是我的重定向代码:

//User::Redirect
public function redirect($url = SITE_URL, $isAjax = false) {
    if ($isAjax === true) {
        //its ajax call, echo js redirect
        echo '<script>window.location = ' . $url . ';</script>';
    } else {
        header("Location: {$url}");
    }
    exit;
}

登录校验代码:

//Basecontroller::__construct
if ( ! $this->user->isLoggedIn()) {
   //redirect to login page
   $this->user->redirect('/login', $request->ajax()); 
   exit;
}

但不是在 ajax 上重定向调用它只是输出 <script>window.location = URL</script>

注意:

我知道我可以在我的每个 AJAX 调用上添加检查以从那里进行重定向,但我试图避免这种情况并让我的 PHP 脚本在基本 Controller 中检测并重定向,而不是我在我的所有 AJAX 调用中添加检查(很多).

最佳答案

您的 Javascript 重定向需要脚本标签。试试这个:

public function redirect($url = SITE_URL, $isAjax = false) {
    if ($isAjax === true) {
        //its ajax call, echo js redirect
        echo '<script>window.location = ' . $url . ';</script>';
    } else {
        header("Location: {$url}");
    }
    exit;
}

就在你的 ajax 中处理这个而言,假设 jQuery

$.ajax(
    {
        type: "POST",
        url: url,
        data: postParams,
        success: function(data)
        {
            //do something with success response
        },
        error : function(httpObj, txtStatus)
        {
            if(httpObj.status == 401)
            {//redirect to login
                var loginUrl = '/login';
                document.location.href = loginUrl;
            }
            else if(httpObj.status == ...)  //etc
            {//do something

            }
            else
            {
                alert("Ajax\n Error: " + txtStatus + "\n HTTP Status: " + httpObj.status);
            }
        }

关于php - 从 PHP 调用 Jquery AJAX 后强制重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091096/

相关文章:

php - 如何将它从 PHP 转换为 JavaScript?

php - 如何强制用户注销symfony2

php - WordPress 5.0 删除讨论元框

javascript - 使用 CKEditor、BLOB 字段和 Rails 4 自定义上传图像

http - 使用nginx将具体路径从http重写为https

php - 如何在 PHP CodeIgniter 中创建 Cron 作业

javascript - 从数据库中检索自上次更新以来的新条目

javascript - 使用 javascript 分解重复的相似 div block 的使用

php - 为什么要手动调用 exit() 方法,而由于 header ("location: ..."而无法访问该方法?

reactjs - 如何将 AWS Elb 后面的 ReactJs SPA 的 http 重定向到 https?