js实现ajax的用户简单登入功能

本文实例为大家分享了js实现ajax的用户简单登入的具体代码,供大家参考,具体内容如下

原生js实现ajax

html页面

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>ajax登录</title>
</head>
<body>
<div>
 <div id="showInfo"></div>
 <form 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('post',url,false);

  //这段代码在xhr.send();执行完之后才能执行
  //这件事做完了怎么办
  //事情办完之后干什么
  xhr.onreadystatechange = function(){
  if(xhr.readyState == 4){
   if(xhr.status == 200){
   alert(1);
   var data = xhr.responseText;
   if(data == 1){
    document.getElementById('showInfo').innerHTML = '用户名或者密码错误';
   }else if(data == 2){
    document.getElementById('showInfo').innerHTML = '登录成功';
   }
   }
  };
  }
  //实际的去做这件事
  //去做这件事情
  xhr.send(null);
  alert(2);
 }
 }

 </script>
</body>
</html>

check.php

<?php 
$username = $_GET['username'];
$password = $_GET['password'];

if($username == 'admin' && $password == '123'){
 echo 2;
}else{
 echo 1;
}
?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。