我有一个自定义框架,我在我的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/