<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ajax</title> <script> function info(){ var username=document.getElementById('username');
//处理特殊字符 var user_value=encodeURIComponent(username.value); var xhr=new XMLHttpRequest(); //准备向服务器发送请求的一些东西 //xhr.open(type,url,同步还是异步); xhr.open('get','index.php?username='+user_value,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ //alert(xhr.resposenText); //console.log(xhr.responseText); document.getElementById('msg').innerHTML=xhr.responseText; } } //发送到服务器 xhr.send(); } </script> </head> <body> 用户名:<input type="text" id="username" onblur="info()"><span id="msg"></span><br/> </body> </html>
<?php $users=['zhangsan','lisi','wangwu']; if(in_array($_GET['username'],$users)){ echo '<font color="red">sorry,用户名已存在</font>'; }else{ echo '<font color="green">恭喜,该用户名可用</font>'; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ajax</title> <script> function info(){ var username=document.getElementById('username');
//处理特殊字符 var user_value=encodeURIComponent(username.value); var xhr=new XMLHttpRequest(); //准备向服务器发送请求的一些东西 //xhr.open(type,url,同步还是异步); xhr.open('post','index.php',true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ //alert(xhr.resposenText); //console.log(xhr.responseText); document.getElementById('msg').innerHTML=xhr.responseText; } } //使用post放松,指定头信息 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //发送到服务器 xhr.send('name='+user_value); } </script> </head> <body> 用户名:<input type="text" id="username" onblur="info()"><span id="msg"></span><br/> </body> </html>
<?php $users=['zhangsan','lisi','wangwu']; if(in_array($_POST['name'],$users)){ echo '<font color="red">sorry,用户名已存在</font>'; }else{ echo '<font color="green">恭喜,该用户名可用</font>'; }