1

我创建了登录页面,该页面将 ajax 请求发送到 php 页面以进行登录验证。在那个 php 页面上,我正在创建会话,并根据登录验证发送响应。如果用户通过身份验证,我会将其从我发送 ajax 的 java 脚本重定向到主页。但是在那个主页上我不能得到那个会话对象......为什么?你能告诉我在主页上检索该会话的解决方案吗

4

1 回答 1

1

我不确定我的做法是否正确,但它对我有用(我希望我没有忘记任何事情):

这是我的 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' 
于 2010-03-16T10:29:55.127 回答