2013-01-19 76 views
0

我已经在PHP上完成了用户注册和登录系统。它工作正常,但现在我试图发送POST请求与Ajax留在同一页面,并且responseText返回空。我已经尝试了一些我在类似问题中看到的解决方案,但他们都没有为我工作。Ajax&PHP,responseText返回空

这是PHP的功能我用它来登录的用户:

if(!empty($_POST)) { 
    $query = " 
     SELECT 
      id, 
      username, 
      password, 
      salt, 
      email 
     FROM users 
     WHERE 
      username = ? 
    "; 

    try { 
     $stmt = $db->prepare($query); 
     $stmt->bind_param("s", $_POST['username']); 
     $result = $stmt->execute(); 
    } 
    catch(Exception $ex) { 
     die("Failed to execute the query"); 
    } 

    // Is logged in? 
    $login_ok = false; 

    $res = $stmt->get_result(); 
    $row = $res->fetch_assoc(); 

    if($row) { 
     // Hash the submitted password and compare it whit the hashed version that is stored in the database 
     $check_password = hash('sha256', $_POST['password'] . $row['salt']); 

     for($n = 0; $n < 65536; $n++) { 
      $check_password = hash('sha256', $check_password . $row['salt']); 
     } 

     if($check_password === $row['password']) { 
      $login_ok = true; 
     } else { 
      echo "Incorrect password"; 
     } 
    } 

    if($login_ok) { 
     unset($row['salt']); 
     unset($row['password']); 

     $_SESSION['user'] = $row; 

     echo "Logged in"; 
    } else { 
     echo "Login failed"; 
    } 
} 

这是我的形式和Ajax功能:

<form action="" method="post"> 
    <fieldset> 
     <legend>Login</legend> 
     <input type="text" name="username" placeholder="user" value="" /> 
     <input type="password" name="password" placeholder="pass" value="" /> 
     <input type="button" id="log" value="Login" onclick="log()"/> 
    </fieldset> 
</form> 

<script type="text/javascript"> 
    function log(){ 
     if (!window.XMLHttpRequest) return; 
     var url = "php/login.php", 
      req = new XMLHttpRequest(); 

     req.open("POST", url); 
     req.send(null); 

     req.onreadystatechange = function(){ 
      if(req.readyState == 4 && req.status == 200){ 
       var response = req.responseText; 
       alert(response); 
      } 
     } 
    } 
</script> 

任何想法?

编辑:我试图不使用jQuery btw。

+0

它看起来不像你发送任何POST数据在该Ajax请求。因此你的第一个PHP条件不符合。 'if(!empty($ _ POST))'。尝试粘贴一个“其他回声”没有POST数据“;'结束双重检查。 – diggersworld

+0

你是对的。我从另一个请求中复制了ajax代码,并忘记了发布数据。我不能相信我花了两个小时试图解决它,并没有看到-_-。谢谢 – nahl

回答

0

在这里添加答案,以便它可以被接受,以便其他SO用户不会打这个页面认为这是一个没有答案的问题。

您示例代码中的问题是没有POST数据与AJAX请求一起发送。

因此,您的第一个条件:if (!empty($_POST))等于FALSE,结果没有条件内的代码运行。