JQuery ajax verify username exists

巴扎黑
Release: 2023-03-02 18:06:01
Original
1209 people have browsed it

Actually, there are many examples of this on the Internet, but when I was doing it, I ran into some problems, and finally found a solution to the problem, so I wanted to post it and record it as a warning.

The code is as follows:

<form name="add" method="post" action="test.php">  
  用户名:<input type="text" id="uname" name="username" />  
</form>
Copy after login
$(&#39;#cname&#39;).blur(function(){  
        if($(&#39;#uname&#39;).val() == &#39;&#39;){  
            $(&#39;#result&#39;).html("<span style=&#39;color:red;&#39;>不能为空</span>");  
        }  
        else{  
            //var str = &#39;cname=&#39;+$(&#39;#cname&#39;).val();  
            $.get(&#39;test.php&#39;,{username:$(&#39;#uname&#39;).val()},function(data){  
                $(&#39;#result&#39;).html("<span style=&#39;color:red;&#39;>"+data+"</span>");  
            });  
        }  
    });
Copy after login
<?php   
mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;);  
mysql_select_db(&#39;news&#39;);  
mysql_query(&#39;set names utf8&#39;);  
$a = $_GET[&#39;cname&#39;];  
$sql = "select * from tnewscategory where cCategoryName = &#39;$a&#39;";  
// $sql = "select count(*) from tnewscategory where cCategoryName = &#39;$a&#39;";  
/* 
问题就出在这个地方了,我原来用的是count(*)的查询语句查询的,但是验证的结果都是可以注册,不管是数据库里已存在的,还是未存在的数据,都提示可以注册,后来换成 select * 就正常了。这两种查询方法,最终的查询结果都是一个资源类型的。最终使用mysql_num_rows()转化后,也确实得了一个数值,却不知道为何返回到ajax验证的时候,却无法成功。当初使用count(*);  想着这种效率更快些,不想却出了这样的情况,暂时记录下吧,以后找到原因,再做更新 
*/  
$n = mysql_num_rows(mysql_query($sql));  
if($n > 0){  
   echo "已存在";  
   exit;  
}  
else{  
    echo "可以注册";  
    exit;  
  
}  
?>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!