【问题标题】:Ajax and sessionAjax 和会话
【发布时间】:2014-07-13 21:06:01
【问题描述】:

我有一个 create_event.php 页面。填写完活动详情后,用户可以登录。成功登录后,我希望用户在同一页面上阅读“您好 $username,您现在已登录”(无需重新加载)。

对于登录过程,我使用以下 Ajax 脚本

$.ajax({
                type : "POST",
                url : "system/process_login.php",
                data : query,
                cache : false,
                success : function(response) {
                    if (response === 'error') {
                        $('.feedback_message').text('Connection to database failed.');
                    };
                    if (response === 'failed') {
                        $('.feedback_message').text('Wrong login details.');
                    }
                    if (response === 'success') {
                        $('#step_login').text('Login successful!');
                    }
                }
            });

我想知道当 ajax 登录过程成功时如何初始化会话。在我的 process_login.php 我写了以下内容:

 session_start();

require_once 'db.php';

// Get values sent via ajax and prepare them for database
$username = $db -> real_escape_string($_REQUEST['username']);
$password = $db -> real_escape_string($_REQUEST['password']);

// Hash password
$password_hashed = sha1($password);


// Check if login information is correct
$query = "SELECT * FROM users WHERE username='$username' AND password='$password_hashed'";
$results = $db -> query($query);
if ($db -> error) {
    $response = 'error';
    echo $response;
}
if (mysqli_num_rows($results) > 0) {
    $_SESSION['username'] = $username;
    $response = 'success';
    echo $response;
} else {
    $response = 'failed';
    echo $response;
}

?>

我的问题:ajax 登录过程成功后,$_SESSION['username'] 变量是否可用?我怎样才能找回它? 在同一页面的上角,即我的 create_event.php,我希望用户阅读“Hello $username, you are logged-in now!”.. .

【问题讨论】:

  • 您必须返回用户名以响应 ajax 调用
  • 而不是 $response = 'success';$response = $username; 并将其与 jquery 一起使用
  • 不要混淆 PHP 和 Javascript 变量。 PHP 会话变量是完全可用的 - 即服务器端。如果您希望它在客户端可用,则必须以某种方式将其发送给客户端。
  • @RenéRoth 我只想在用户点击登录后开始一个会话。我怎么能意识到这一点?
  • 你已经在这样做了。

标签: javascript php jquery ajax session


【解决方案1】:

以下 cmets (未经测试)

php

if (mysqli_num_rows($results) > 0) {
    $user = $_SESSION['username']; // or, other method(s) of deriving accurate `username` / `user`
    $response = $user;
    echo $response;
}

js

success : function(response) {
                    if (response === 'error') {
                        $('.feedback_message').text('Connection to database failed.');
                    };
                    if (response === 'failed') {
                        $('.feedback_message').text('Wrong login details.');
                    }
                    if (response != "error" && response != "failed") {
                        $('#step_login').text("Hello" + response + ", you are logged-in now!");
                    }
                }

【讨论】:

    猜你喜欢
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2023-03-25
    • 2012-12-12
    • 2011-08-03
    相关资源
    最近更新 更多