本文實(shí)例講述了ThinkPHP框架結(jié)合Ajax實(shí)現(xiàn)用戶名校驗(yàn)功能。分享給大家供大家參考,具體如下:
在模板文件中通過ajax獲取到用戶名,然后在控制器中將用戶名與數(shù)據(jù)庫比較,返回校驗(yàn)結(jié)果給模板文件。
模板文件路徑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無刷新方式校驗(yàn)用戶名 function checkname(){ //(1)獲取被校驗(yàn)的用戶名信息 var nm = document.getElementById('User_username').value; //(2)ajax抓取到用戶名傳遞給服務(wù)器端進(jìn)行校驗(yàn) var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ document.getElementById('namecheck').innerHTML = xhr.responseText; } } //tp框架使用模式:分組/控制器/操作方法/方法參數(shù) //xhr.open('get', "/shop/index.php/User/checkNM/" + nm);//默認(rèn)分組為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{ //用戶名校驗(yàn) function checkNM( $name ){ //在數(shù)據(jù)庫中根據(jù)條件查詢結(jié)果 $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程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/Yeoman92/article/details/53159538