从PHP调用Jquery AJAX后强制重定向
我有一个自定义框架,我在我的请求文件中检测请求是否是ajax。在我的basecontroller中,我检查用户是否登录:从PHP调用Jquery AJAX后强制重定向,php,jquery,http-redirect,Php,Jquery,Http Redirect,我有一个自定义框架,我在我的请求文件中检测请求是否是ajax。在我的basecontroller中,我检查用户是否登录: 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::Redire
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;
}
但是它不是在ajax调用上重定向,而是输出window.location=URL
注意:
我知道我可以在每个AJAX调用上添加检查以执行重定向,但我试图避免这种情况,让我的PHP脚本在基本控制器中检测并重定向,而不是在所有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;
}
客户机如何知道这是javascript 尝试用脚本标记将其包围 i、 e
window.location='testpage.html'
这个代码对我很有用。如果ajax调用发现用户未登录(例如:用户保持浏览器打开且会话已过期),PHP将以JS或meta标记的形式向浏览器回显刷新代码,以强制刷新整个页面
$url = '/index.php';
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>';
$url='/index.php';
回声';
echo'window.location.href=“”.$url.“;”;
回声';
回声';
回声';
回声';
作为一项建议,我倾向于通过一个通用函数传递所有ajax调用,如果发送了一个,该函数将处理http重定向。因此,您有一个包含所有ajax调用的大文件?不,我有一个小文件,其中包含一个通用ajax函数,有两个不同用途的变体,但最终每个请求都会通过相同的函数。你是指用来调用所有ajax的Javascript函数吗?是的。所以我所有的ajax调用都以某种方式通过这个函数,这个函数处理各种http响应,包括重定向。看看上面Nick的回复。即使使用htmladd,这行标题(“HTTP/1.1 401未经授权”)仍然没有任何内容代码>
$.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);
}
}
<html>
<script>
window.location = 'testpage.html'
</script>
</html>
$url = '/index.php';
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>';