我有简单的jquery& php reg /登录脚本工作。基本上如果用户的名字和传递在数据库中,那么php回应为真,并且在我的javascript中我有
我想将用户名传回我的javascript并将其保存在变量中,我该怎么做?
我想在我的php中我可以这样:
json_encode(array("boolean" => "true", "username" => '$username'));
但我如何在jQuery中处理它呢?
$('#login').click(function(e){
$.get("login.php",{username: $("#username").val(), password: $("#password").val()},function(data){
if(data == "true"){
alert("Logged in");
$('#logindiv').slideUp();
$('#gamediv').show();
$('#registerdiv').hide();
$('#gameheader').html(userloggedin);
}else{
alert("Not Logged in");
}
});
});
修改 的login.php
if (isset($_GET['username'])&& isset($_GET['password'])) {
$username = $_GET['username'];
$password = $_GET['password'];
$sql = mysql_query("SELECT * FROM members WHERE username='$username' AND password='$password'") or die(mysql_error());
// Get member ID into a session variable
$id = $row["id"];
session_register('id');
$_SESSION['id'] = $id;
// Get member username into a session variable
$username = $row["username"];
session_register('username');
$_SESSION['username'] = $username;
$json = array("boolean" => "true", "username" => $username);
echo(json_encode($json));
//exit();
} else {
echo "false";
}
main.html中 ...
$('#login').click(function(e){
$.getJSON("login.php",{username: $("#username").val(), password: $("#password").val()},function(data){
if(data.username!==undefined){
alert(data.username);
$('#logindiv').slideUp();
$('#gamediv').show();
$('#registerdiv').hide();
$('#gameheader').html(data['username']);
}else{
}
});
});
答案 0 :(得分:2)
用户名将在$ .get:
返回的数据对象中 $.get('login.php',params, function(data){
if(data){
alert(data.username); // that's the value from php
}
}
您可以对值进行大量检查:
...
if(data.username) // username isn't empty string, null, undefined
if(data.username!==undefined) // if you got it at all
答案 1 :(得分:1)