案例:簡單驗(yàn)證用戶名是否存在(post請(qǐng)求)
案例需求:
我們這里用php數(shù)組模擬一個(gè)數(shù)據(jù)庫,然后運(yùn)用onblur事件通過Ajax實(shí)現(xiàn)用戶名驗(yàn)證是否可以近上。
-
js代碼
<script> window.onload = function(){ var username = document.getElementById('username'); var pwd = document.getElementById('password'); username.onblur = function(){ var userValue = username.value; //1.創(chuàng)建XMLHttpRequest對(duì)象 var xhr = null; if( window.XMLHttpRequest ){ xhr = new XMLHttpRequest(); //常規(guī)瀏覽器 }else{ xhr = new ActiveXObject( "Microsoft.XMLHTTP" ); //IE6 } //2.準(zhǔn)備發(fā)送 var str = 'username =' + userValue; xhr.open( 'post','demo-post.php',true ); //3.執(zhí)行發(fā)送動(dòng)作 //post請(qǐng)求必須設(shè)置請(qǐng)求頭 setRequestHeader xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(str); //post請(qǐng)求時(shí)這里是傳送到服務(wù)器端的字符串 //4.指定回調(diào)函數(shù) 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"; } ?>