本文實例講述了ThinkPHP框架結合Ajax實現用戶名校驗功能。分享給大家供大家參考,具體如下:
在模板文件中通過ajax獲取到用戶名,然后在控制器中將用戶名與數據庫比較,返回校驗結果給模板文件。
模板文件路徑shop/Home/View/User/register.html
<!--register.html--><!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>Untitled Document</title><script type="text/javascript"> var urlpath = "{$smarty.const.__CONTROLLER__}"; //ajax無刷新方式校驗用戶名 function checkname(){ //(1)獲取被校驗的用戶名信息 var nm = document.getElementById('User_username').value; //(2)ajax抓取到用戶名傳遞給服務器端進行校驗 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ document.getElementById('namecheck').innerHTML = xhr.responseText; } } //tp框架使用模式:分組/控制器/操作方法/方法參數 //xhr.open('get', "/shop/index.php/User/checkNM/" + nm);//默認分組為Home xhr.open('get', urlpath + "/checkNM/" + nm); }</script></head><body> <tr> <td> <label for="User_username">用戶名</label> </td> <td> <input type="text" name="username" value="" id="User_username" onblur="checkname()"> <span id="namecheck">{$errorInfo.username|default:""}</span> </td> </tr></body></html>
控制器文件路徑shop/Home/Controller/User/UserController.class.php
<?php//UserController.class.php//命名空間namespace Home/Controller;use Think/Controller;//前臺用戶控制器class UserController extends Controller{ //用戶名校驗 function checkNM($name){ //在數據庫中根據條件查詢結果 $info = D('User')->where("username='$name'")->find(); if($info){ echo "<span style='color:red'>用戶名已存在,請換一個</span>"; }else { echo "<span style='color:green'>恭喜,用戶名可以使用</span>"; } exit; }}
希望本文所述對大家基于ThinkPHP框架的PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選