0

我有我的简单 jquery & php reg/login 脚本工作。基本上,如果用户的姓名和通行证在数据库中,则 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";
}

主.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{

         }
      });
});
4

2 回答 2

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 
于 2012-07-09T15:41:56.993 回答
1

使用 .getJSON():http ://api.jquery.com/jQuery.getJSON/

然后只需使用

data.username
于 2012-07-09T15:42:25.987 回答