使用AJAX&进行身份验证的PHP [英] Authentication using AJAX & PHP

查看:65
本文介绍了使用AJAX&进行身份验证的PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
?>

推荐答案

我更改以下代码

xmlhttp.onReadystatechange

xmlhttp.onreadystatechange

,并且有效.并在输入 type ="submit" 中使用 onclick ="checkLogin();返回false;" .

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

这篇关于使用AJAX&amp;进行身份验证的PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆