我正在制作一个注销按钮,它通过AJAX调用调用PHP脚本但不知何故我的php没有重定向。此外,当我尝试使用JavaScript时,它也无法正常工作。
我尝试了以下事项:
ob_start()
和ob_end_flush()
exit;
更改为exit();
header("Location: http://localhost/page_login.html)
到echo("<script>location.href = http://localhost/page_login.html';</script>");
当我直接在我的URL中打开php脚本时(只需输入),它会将我重定向到page.login.html但是从ajax调用它不是。当我打印数据时,它会打印page_login.html文件,该文件也会排除不在正确地图中的选项。
任何有关如何解决这个问题的想法?
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="logout_button">
Logout
</div>
<script src="jquery-3.2.1.js"></script>
<script src="logout.js" type="text/javascript"></script>
</body></html>
JAVASCRIPT(logout.js)
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
console.log(data);
}
});
})
PHP(logout.php)
<?php
header('Location: http://localhost/page_home.html');
exit;
?>
答案 0 :(得分:2)
当您直接调用您的php文件时,header('Location: http://localhost/page_home.html');
将位置字段添加到HTTP标头,告诉浏览器将用户重定向到指定位置。
如果你通过ajax调用它,jQuery并不关心这个头字段。
你需要的是:
$('#logout_button').click(function(){
//Insert your ajax call here if you need to do something server side like destroy the session
window.location.replace('http://localhost/page_home.html');
})
编辑:正如评论中所提到的,使用指向其中header('Location: http://localhost/page_home.html');
的logout.php的链接会更简单。
答案 1 :(得分:2)
在ajax中的Javascript中使用location.href
来重定向或重新加载,而不是在.php
文件中
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
dataType: "json",
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
location.href = "/page_home.html";
//console.log(data);
}
});
});
同时将回复数据从.php
发送到logout/session destroy
,例如
<?php
// Code here to logout or session destroy
// return json or string
$response["success"] = true;
echo json_encode($response);
?>
答案 2 :(得分:2)
您对AJAX在这种情况下的工作方式存在误解。当您执行AJAX调用时,会将一个单独的请求作为您的POST发送到给定的URL。这本身并不会影响您在客户端窗口中的原始页面。基本上,正在发生的事情是:
logout.php
发送请求logout.php
运行其代码并返回对原始页面的响应(在这种情况下成功/失败;如果您的PHP页面中有return
,则返回一些数据)这里的AJAX只是在两个页面之间共享信息的一种方式,而不是连续运行它们。您需要做的是重定向原始页面,您可以使用JavaScript执行此操作!毕竟,不要忘记JavaScript是我们的客户端语言,PHP是服务器端语言。
您可以在JavaScript中找到重定向的方法。例如,在这种情况下您可以使用window.location.href
:
$('#logout_button').click(function(){
$.ajax({
type: 'POST',
url: 'logout.php',
error: function(response) { console.log(JSON.stringify(response))},
success: function(data){
window.location.href = "http://localhost/page_home.html";
console.log(data);
}
});
});