AJAX在将php5升级到php7后不起作用



在我的原始php5代码中,一旦用户打开索引页面,就会有一个ajax调用来检查是否存储了任何$_SESSION['user']。如果存在会话,则会显示用户。否则,页面将重定向到登录页面。一旦我升级到php7,它就停止工作了。

$.ajax({
type: 'POST',
url: "php/checksession.php",
})
.done(function(response) {
console.log(response);
var code = response[0].code;
///// if no loging session is stored, redirect back to loging page
if (code == 0) {
window.location.href = "login";
///// Session is found, update balance 
} else {
$('body').show();
///////////////////// Do other stuff	
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>Title Goes Here</title>
</head>
<body style="display:none">
<p>PageContent</p> 
</body> 
</html>

这是php7代码。

<?php
header('Content-type: application/json');
require 'connection.php';
// Get Access to DB
// if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST))
{
ob_start();
session_start();
if (isset($_SESSION['user']))
{
$responseArray = array(
'code' => '1',
'type' => 'good',
'message' => 'found'
);
}
else
{
$responseArray = array(
'code' => '0',
'type' => 'bad',
'message' => 'no session'
);
}
}
else
{
$responseArray = array(
'code' => '0',
'type' => 'bad',
'message' => 'no POST'
);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$Arrays = [];
array_push($Arrays, $responseArray);
$encoded = json_encode($Arrays);
header('Content-Type: application/json');
echo $encoded;
}
else
{
echo $responseArray['message'];
} // else just display the message
?>

$_POST为空,Json数据不会发送回浏览器,因为不满足以下语句:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

尝试使用另一种方法来获取POST数据。。。。我不知道为什么,但当我使用AJAX时,POST数据有时会变成另一种方式。。。

<?php
if(!isset($_POST)) {
$_POST = json_decode(file_get_contents("php://input"));
}

最新更新