我创建了登录页面,它将 ajax 请求发送到 php 页面以进行登录验证。 在该 php 页面上,我正在创建 session ,并根据登录验证发送响应。 如果用户通过身份验证,我将其从发送ajax的java脚本重定向到主页。但在那个主页上我无法获取该 session 对象...为什么?你能告诉我在主页上检索该 session 的解决方案
最佳答案
我不确定我的做法是否正确,但这种方式对我有用(我希望我没有忘记任何事情):
这是我的login.php 的作用:
header('Content-type: text/json');
// here : import files I need
session_start();
// here : load some parameters into session variables
// here : init mysql connection
// here : get user and password from $_POST and check them against the database
// If the user can't connect, return an error to the client
if ( ! $ok )
{
echo '{ "ok": "N" }';
exit;
}
$_SESSION['user'] = $user;
echo '{ "ok": "O" }';
?>
然后,当我访问另一个 php 文件时,它是这样开始的:
header('Content-type: text/json');
// again, required files go here
session_start();
if ( ! isset($_SESSION['user'] )) {
echo '{ "ok": "N" }';
exit;
}
$user=$_SESSION['user'];
....
我进行的每个 ajax 调用都会检查结果是否告诉我用户未连接,如果没有连接,则返回到登录页面。
$.ajax({
type: "POST",
url: "myphp.php",
dataType: "json",
data: somedatatopost,
success: function(pRep){
if (!pRep) {
alert("No response from the server.");
return;
}
if (pRep.ok=="N") {
window.location = '/index.html';
return;
}
// here is where I handle a successful response
}
});
对于登录ajax调用,我有:
[....]
// here is where I handle a successful response
window.location='mynewpage.html'
关于php - ajax登录问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2452318/