我试图写非常简单的AJAX,但有一些问题。这是我的ajax代码:
<div id="userHeader">
<img src="/images/logout.png" alt="logout" title="exit" onclick="ajaxLogOut()" style="cursor: pointer;">
</div>
<script type="text/javascript">
function ajaxLogOut(){
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/user/logout.php",true);
xmlhttp.send();
// location.reload();
}
和我的logout.php:
<?php
session_start();
if (isset($_SESSION['log_in'])) {
unset($_SESSION['log_in']);
unset($_SESSION['username']);
session_destroy();
}
?>
问题是当我注释location.reload()并手动重新加载页面时,它会工作。如果取消注释,页面会刷新,但我还是登录了
Try:
xmlhttp.open("GET","/user/logout.php",false);//sync mode
Or (Async mode with callbak) -推荐:
xmlhttp.open("GET","/user/logout.php",true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
location.reload();
}
}
xmlhttp.send(null);