dti70601
2013-03-20 00:20
浏览 23
已采纳

使用AJAX和PHP进行身份验证

I make a simple program to simulate authentication using AJAX and PHP. The following is my code. It will redirect to "/?" but nothing happened. I tried to use checkLogin(); return false; in onclick event but it didn't work.

index.php

<script type="text/javascript" src="validation.js"></script>
<form>
    <p>
        <label>Username <abbr title="Required">*</abbr></label>
        <input id="usernamelogin" type="text" value="" />
    </p>
    <p>
        <label>Password <abbr title="Required">*</abbr></label>
        <input id="passwordlogin" type="text" value="" />
    </p>                
    <p>
        <input id="login" type="submit" value="Login" onclick="checkLogin()" />
    </p>
</form>

validation.js

function checkLogin(){
    var u = document.getElementById("usernamelogin").value;
    var p = document.getElementById("passwordlogin").value;

    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }
    else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onReadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            if(xmlhttp.responseText == u){
                alert(':)');
            }
            else{
                alert(':(');
            }
        }
    }

    xmlhttp.open("GET", "login.php?u=" + u + "&p=" + p, true);
    xmlhttp.send(); 
}

login.php

<?php
    $u = $_GET['u'];
    $p = $_GET['p'];

    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $db = 'db';

    $con = mysql_connect($host, $user, $pass);
    if(!$con) die("Could not connect: " . mysql_error());

    mysql_select_db($db, $con);
    $query = "select username from login where username = '" . $u . "' and password = '" . $p . "'";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    echo $row['username'];
    mysql_close($con);
?>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyulan6251 2013-03-20 01:04
    已采纳

    I change the following code

    xmlhttp.onReadystatechange
    

    to

    xmlhttp.onreadystatechange
    

    and it works. And also use onclick="checkLogin(); return false;" in input type="submit".

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题