Ajax无按钮模式
本篇幅为实现注册页面无需提交按钮自动判断用户名是否存在
前言
这里我使用的是php
环境,进行学习
php
环境搭建可以直接使用phpstudy
ajax
原理部分,可取隔壁看原理
代码实现
首先我们创建一个页面表单,用来输入数据,由于这里是用ajax
实现的用户名判断,form
表单中可以不设置action
和method
属性值
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <title> 验证表单 </title> <body> <form> <table> <tr> <td>用户名:</td> <td> <input type="text" name="test" id="user"> </td> <td> <span id="span"></span> </td> </tr> <tr> <td>密码:</td> <td> <input type="test" name="pwd" id="pass"> </td> <td><span></span></td> </tr> </table> </form> </body> </html>
|
后端代码如下
1 2 3 4 5 6 7 8
| <?php $test = $_POST['user']; if($test == 'admin'){ echo 'no'; }else{ echo 'ok'; } ?>
|
可以正常输出,如下图

ajax
实现,使用js
写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <script> window.onload=function(){ var username = this.document.getElementById("user"); var pass = this.document.getElementById("pass");
username.onblur=function(){ var userValue = username.value; console.log(userValue)
var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
xhr.open("post","http://127.0.0.1/test/ajax/1.php",true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8"); var user = "user="+userValue; console.log(user) xhr.send(user);
xhr.onreadystatechange=function(){ if (xhr.readyState == 4 && xhr.status == 200){ var request = xhr.responseText; if (request == "ok"){ document.getElementById("span").innerText="用户名可以使用"; }else{ document.getElementById("span").innerText="用户名已存在"; } } }
}
} </script>
|
实现效果图,如下



就这样吧,代码解释在注释里面都写了