使用AJAX的身份验证&;PHP


Authentication using AJAX & PHP

我制作了一个简单的程序来模拟使用AJAX和PHP的身份验证。以下是我的代码。它将重定向到"/?",但什么也没发生。我尝试在onclick事件中使用checkLogin(); return false;,但没有成功。

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>

验证.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);
?>

我更改了以下代码

xmlhttp.onReadystatechange

xmlhttp.onreadystatechange

它是有效的。并在输入type="submit"中使用onclick="checkLogin(); return false;"

您可以做的是从输入type="submit"中删除onclick事件,并将其添加到表单中:

<form onsubmit="return checkLogin()">

要让这个工作,你必须添加

return false

到您的javascript函数,就在您关闭函数

之前