<body> <form name="form_register"> <input type="text" id="username" name="username" size="20"> <input type="button" value="查看用户名是否被占用" onclick="javascript:chkUsername(form_register.username.value)"> </form> </body> <script type="text/javascript"> function chkUsername(username){ if(username==""){ alert('请输入用户名'); }else{ $.get('server.php',{"username":username},function(data){ if(data=='y') { alert("该用户名已经被注册"); }else{ alert("该用户名可以使用"); } }); } } </script>
server.php
<?php $str=$_GET['username']; $str1=trim($str); $host='127.0.0.1'; $userName='root'; $password=''; $database='test'; $conn=mysqli_connect($host,$userName,$password,$database); mysqli_query($conn,'set names utf8'); $sql=mysqli_query($conn,"select id,username from login where username='$str1'"); if (!$sql) { printf("Error: %s ", mysqli_error($sql)); exit(); } $result=mysqli_fetch_array($sql,MYSQLI_ASSOC); if($result){ echo "y"; }else{ echo "n"; }