1

ログイン確認のためにphpページにajaxリクエストを送信するログインページを作成しました。その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 に答える