我在 jQuery mobile 和 php 中制作了一个登录脚本。php 文件设置一个创建会话并设置 $_SESSION['myusername']。我可以从 login.html 页面的会话变量中检索用户名还是必须执行 'var myusername = data.username;' 然后在登录页面上以某种方式将此 var 传递给 loggedin.html 页面。
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
$host="localhost"; // Host name
$dbusername="root"; // Mysql username
$password=""; // Mysql password
$db_name="testDB"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$dbusername", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$sql="SELECT * FROM members WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
while($row = mysql_fetch_array($sql)){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("session_username");
session_register("session_password");
$id = $row["id"];
session_register('id');
$_SESSION['id'] = $id;
session_register('username');
$_SESSION['username'] = $myusername;
mysql_query("UPDATE members SET last_log_date=now() WHERE id='$id' LIMIT 1");
}
$json = array('boolean' => true, 'jsonUser' => $_SESSION['username']);
echo json_encode($json);
}
else {
echo "Wrong Username or Password";
}
?>
编辑:
var user="<?php echo $myusername; ?>";
$(document).ready(function(e) {
$('#usernamediv').html(user);
});