PHP+AJAX实时检查帐号是否被注册代码
三月 06, 2019 | views
Comments 0
实时检查帐号是否被注册代码是现在WEB应用中用到非常多的一个功能,这样主要是为用户体验好了,不要等待用户提交数据时再告诉对方说已经被注册了,这样非常的不错了,我们可以在用户输入完之后就验证了,下面来看一个简单的例子.
数据库部分:
- CREATE TABLE `username_list` (
- `id` int(11) NOT NULL auto_increment,
- `username` varchar(60) character set latin1 NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
js代码:
- <script type="text/<a href="/js_a/js.html" target="_blank">javascript</a>"> $(document).ready(function() { $("#username").keyup(function (e) { //removes spaces from username $(this).val($(this).val().replace(/s/g, '')); var username = $(this).val(); if(username.length < 4){$("#user-result").html('');return;} if(username.length >= 4){ $("#user-result").html('<img src="imgs/ajax-loader.gif" />'); $.post('check_username.php', {'username':username}, function(data) { $("#user-result").html(data); }); } }); });
- </script>
XML/HTML Code
- <div id="registration-form"> <label for="username">输入帐号: <input name="username" type="text" id="username" maxlength="15"> <span id="user-result"></span> </label> <br>输入的字符大于等于4才会检测
- </div>
check_username.php
- <?php
- <a href="/tags.php/include/" target="_blank">include</a>_once("conn.php");
- //check we have username post var
- if(isset($_POST["username"]))
- {
- //check if its ajax <a href="/tags.php/request/" target="_blank">request</a>, exit script if its not
- if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
- die();
- }
- //trim and lowercase username
- $username = strtolower(trim($_POST["username"]));
- //sanitize username
- $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
- //check username in db
- $results = mysql_query("SELECT id FROM username_list WHERE username='$username'");
- //return total count
- $username_exist = mysql_num_rows($results); //total records
- //if value is more than 0, username is not available
- if($username_exist) {
- die('<img src="imgs/not-available.png" />');
- }else{
- die('<img src="imgs/available.png" />');
- }
- //close db connection
- }
- ?>
zend