案例:简单验证用户名是否存在(post请求)
案例需求:
我们这里用php数组模拟一个数据库,然后运用onblur事件通过Ajax实现用户名验证是否可以。
-
js代码
<script> window.onload = function(){ var username = document.getElementById('username'); var pwd = document.getElementById('password'); username.onblur = function(){ var userValue = username.value; //1.创建XMLHttpRequest对象 var xhr = null; if( window.XMLHttpRequest ){ xhr = new XMLHttpRequest(); //常规浏览器 }else{ xhr = new ActiveXObject( "Microsoft.XMLHTTP" ); //IE6 } //2.准备发送 var str = 'username =' + userValue; xhr.open( 'post','demo-post.php',true ); //3.执行发送动作 //post请求必须设置请求头 setRequestHeader xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(str); //post请求时这里是传送到服务器端的字符串 //4.指定回调函数 xhr.onreadystatechange = function(){ if( xhr.readyState == 4 && xhr.status == 200 ){ var data = xhr.responseText; var info = document.getElementById('info'); if( data == '1' ){ info.innerHTML='用户可用'; info.style.color='yellowgreen'; }else if( data == '2' ){ info.innerHTML = '用户名以存在'; info.style.color = 'red'; } } }; }; }; </script>
-
html代码
<form>
用户:<input type="text" name="username" id="username"><span id="info"></span><br>
密码:<input type="password" name="password" id="password">
</form>
-
php代码
<?php $arry = array('super','kobe','admin'); $username = $_POST['username']; $flag = false; foreach ( $arry as $value ) { if( $username == $value ){ $flag = true; break; } } if( $flag == true ){ echo "2"; }else if( $flag == false ) { echo "1"; } ?>
网友评论