本文實例講述了jquery+ajax實現注冊實時驗證。分享給大家供大家參考,具體如下:
當我們注冊一個用戶時,會實時提示該用戶的信息是否可用,這就是ajax的應用,很久以前就看過這個實現了,今天又看了一遍,給記錄下來O(∩_∩)O哈!
先介紹下ajax中$.get,由于$.post用法和$.get大同小異就不再介紹了:
這是一個簡單的 GET 請求功能以取代復雜 $.ajax 。請求成功時可調用回調函數。如果需要在出錯時執行函數,請使用 $.ajax。
$(selector).get(url,data,success(response,status,xhr),dataType)
參數 描述 url 必需。規定將請求發送的哪個 URL。 data 可選。規定連同請求發送到服務器的數據。 success(response,status,xhr)
可選。規定當請求成功時運行的函數。
額外的參數:
response - 包含來自請求的結果數據 status - 包含請求的狀態 xhr - 包含 XMLHttpRequest 對象 dataType可選。規定預計的服務器響應的數據類型。
默認地,jQuery 將智能判斷。
可能的類型:
"xml" "html" "text" "script" "json" "jsonp" 請求 test.php 網頁,忽略返回值:$.get("test.php");
更多示例:
例子 1
請求 test.php 網頁,傳送2個參數,忽略返回值:
$.get("test.php", { name: "John", time: "2pm" } );
例子 2
顯示 test.php 返回值(HTML 或 XML,取決于返回值):
$.get("test.php", function(data){ alert("Data Loaded: " + data); });
例子 3
顯示 test.cgi 返回值(HTML 或 XML,取決于返回值),添加一組請求參數:
$.get("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
下面貼上我的代碼:
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>用戶注冊</title> <script type="text/javascript" src="http://www.gimoo.net/t/1904/jquery/jquery-1.5.2.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#username").focus(); $("#username").keyup(function() { name= $("#username").val();//val()方法返回或設置被選元素的值。 if(len(name)< 4)//調用下面的自定義len函數 $("#username1").html("<font color=red>注冊名稱必須大于等于2位</font>"); else $("#username1").html("<font color=red>符合要求</font>");//html() 方法返回或設置被選元素的內容 (inner HTML)。 }); $("#username").blur(function(){ name= $("#username").val(); $.get("t1.php", { username:name } ,function(data){//判斷數據庫中是否存在此用戶名 重點$.get,$.post t1.php在下面 if(data==1) {$("#username1").html("<font color=green>符合要求</font>");} else {$("#username1").html("<font color=green>已被占用</font>");} }); }); }); function len(s) {//若為漢字之類的字符則占兩個 var l = 0; var a = s.split(""); for (var i=0;i<a.length;i++) { if (a[i].charCodeAt(0)<299) { l++; } else { l+=2; } } return l; } </script> </head> <body> <form name="fram" action="register.php" onsubmit="return docheck();"> <table width="330" border="0" align="center" cellpadding="5" bgcolor="#eeeeee"> <tr> <td>用戶名:</td> <td><input name="username" type="text" id="username" /></td><td><div id="username1"></div></td> </tr> </table> </form> </body> </html>
t1.php:
<?php $link=mysql_connect("localhost","root",""); mysql_select_db("test"); mysql_query("set names utf8");// $sql="select * from user where user='".$_GET['username']."'";// $result=mysql_query($sql) or die(mysql_error()); $num=mysql_affected_rows(); if($num==0) $msg=1; else $msg=0; echo $msg;//返回值 mysql_close($link); ?>
希望本文所述對大家jQuery程序設計有所幫助。