本文實例講述了ThinkPHP框架結合Ajax實現用戶名校驗功能。分享給大家供大家參考,具體如下:
在模板文件中通過ajax獲取到用戶名,然后在控制器中將用戶名與數據庫比較,返回校驗結果給模板文件。
模板文件路徑shop/Home/View/User/register.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<!--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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<?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程序設計有所幫助。
原文鏈接:https://blog.csdn.net/Yeoman92/article/details/53159538