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条)

报告相同问题?

悬赏问题

  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统
  • ¥15 快手联盟怎么快速的跑出建立模型