用原生js的ajax实现用户登录的前后台代码
前台代码

点击(此处)折叠或打开

  1. <!DOCTYPE html >
  2. <html>
  3.  <head>
  4.     <title>task</title>
  5.     </head>
  6.     <body>
  7.      <p><label>用户名</label><input type="text" id="username"/></p>
  8.      <p><label>密码</label><input type="password" id="password"/></p>
  9.      <p><input type="submit" value="submit" onclick="doRequestUsingPOST()"/></p>
  10.     </body>
  11. </html>
  12. <script language="javascript" type="text/javascript">
  13. //创建一个XMLHttpRequest对象
  14.       var xmlHttp;
  15.      function createXMLHttpRequest(){
  16.       if(window.ActiveXObject)
  17.       {
  18.          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  19.       }
  20.       else if(window.XMLHttpRequest)
  21.       {
  22.         xmlHttp = new XMLHttpRequest();
  23.       }else{
  24.      alert("浏览器不支持XMLHttpRequest对象");
  25.      }
  26.     }
  27.     //拼接请求参数
  28. function createQueryString(){
  29.   var username = document.getElementById("username").value;
  30.   var password = document.getElementById("password").value;
  31.   var queryString = "username="+username+"&password="+password;
  32.   return queryString;
  33. }
  34. //开始一个请求
  35. function doRequestUsingPOST(){
  36.    createXMLHttpRequest();
  37.    var url = "dologin.php";
  38.    var queryString = createQueryString();
  39.    xmlHttp.open("POST",url,true);
  40.    xmlHttp.onreadystatechange = handleStateChange;
  41.    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
  42.    xmlHttp.send(queryString);
  43. }
  44. function handleStateChange(){
  45. if(xmlHttp.readyState == 4){
  46.     if(xmlHttp.status == 200){
  47.      console.log(xmlHttp.responseText);
  48.      if(xmlHttp.responseText == "ok"){
  49.      alert("ok");
  50.      }else{
  51.      alert("error");
  52.      }
  53.     }
  54.    }
  55. }

  56. </script>
后台代码dologin.php

点击(此处)折叠或打开

  1. <?php
  2. session_start();
  3. if($_POST['username']&&$_POST['password']){
  4.     $name = $_POST['username'];
  5.     $pass = $_POST['password'];
  6.     if($name=='ella' && $pass = 'pass'){
  7.     
  8.          echo "ok";
  9.      
  10.     }else{
  11.         echo "error";
  12.     }
  13. }else{
  14.     echo 'error';
  15.     exit;
  16. }
  17. ?>
写个demo运行吧

12-17 21:45