1、html代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>ajax登录</title> 6 </head> 7 <body> 8 <div> 9 <form action="" method="post"> 10 <div id="showinfo"></div> 11 用户名:<input type="text" name="username" id="username"/> 12 <br /> 13 密码:<input type="password" name="password" id="password"/> 14 <input type="button" id="btn" value="登录"/> 15 </form> 16 </div> 17 <script type="text/javascript"> 18 window.onload = function(){ 19 var btn = document.getElementById("btn"); 20 btn.onclick = function(){ 21 22 var username = document.getElementById("username").value; 23 var passwords = document.getElementById("password").value 24 25 26 var xhr = null; 27 if(window.XMLHttpRequest){ 28 xhr=new XMLHttpRequest(); 29 }else{ 30 xhr = ActiveXObject("Microsoft.XMLHTTP"); 31 } 32 xhr.open('get','./check.php?username='+username+"&password="+passwords,true); 33 xhr.onreadystatechange = function(){ 34 if(xhr.readyState==4){ 35 if(xhr.status==200){ 36 var data = xhr.responseText; 37 if(data==1){ 38 document.getElementById('showinfo').innerHTML = "用户名或密码错误" 39 }else if(data==2){ 40 document.getElementById('showinfo').innerHTML = "登录成功" 41 42 } 43 } 44 } 45 } 46 xhr.send(null); 47 } 48 } 49 </script> 50 </body> 51 </html>
2、后台代码(此处是php)
1 <?php 2 $username = $_GET['username']; 3 $password = $_GET['password']; 4 5 if($username=='admin' && $password=='123'){ 6 echo 2; 7 }else{ 8 echo 1; 9 } 10 ?>
3、实现结果展示