Ajax简单实例

来源:互联网 发布:淘宝差评会6个月消失吗 编辑:程序博客网 时间:2024/06/16 12:11

HTML部分

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Ajax登陆</title></head><body><div>    <div id="showInfo"></div>    <form action="" id="form">        用户名:<input type="text" name="username" id="username"><br>        密码:<input type="password" name="password" id="password">        <input type="button" id="btn" value="登陆">    </form></div>    <script type="text/javascript">        window.onload = function(){            var btn = document.getElementById('btn');            btn.onclick = function(){                var username = document.getElementById('username').value;                var password = document.getElementById('password').value;            var xhr = null;            if (window.XMLHttpRequest){                xhr = new XMLHttpRequest();            }else{                xhr = new ActiveXObject("Microsoft.XMLHTTP");            }            var url = 'check.php?username='+username+'&password='+password;            xhr.open('get',url, true);            xhr.onreadystatechange = function(){                if(xhr.readyState == 4){                    if(xhr.status == 200){                        var data = xhr.responseText;                        if(data == 1){                            document.getElementById('showInfo').innerHTML = '用户名或密码错误';                        }else if(data == 2){                            document.getElementById('showInfo').innerHTML = '登陆成功';                        }                    }                }            }            xhr.send(null);            }        }    </script></body></html>

PHP部分

<?php$username = $_GET['username'];$password = $_GET['password'];if($username == 'admin' && $password == '123'){    echo 2;}else{    echo 1;}?>
原创粉丝点击