register.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB2312" /> <title>使用jQuery实现AJAX帐号验证效果</title> <mce:script type="text/javascript" src="jquery-1.4.min.js" mce_src="jquery-1.4.min.js"></mce:script> <mce:script type="text/javascript" language="javascript"><!-- $(document).ready(function() { $("#username").blur(function() { var username = $("#username").serialize(); $.ajax({ url:"register_handler.php", // The URL to request. type:"get", // The type of request to make ("POST" or "GET"), default is "GET". data:username, // Data to be sent to the server. dataType:"text", // The type of data that you're expecting back from the server. success:show_result // A function to be called if the request succeeds. }); }); }); function show_result(msg) { if (msg == "true") { $("#result").removeClass().addClass("green") .html("恭喜!该帐号可以使用。"); } else { $("#result").removeClass().addClass("red") .html("对不起!该帐号已经被占用,请尝试其它帐号!"); } } // --></mce:script> <mce:style type="text/css"><!-- .red { border:1px dashed #FF0000; color:#FF0000; font-size:12px; padding:2px 2px 2px 20px; width:280px; background:#FFCCFF url(error.gif) no-repeat 2px center; } .green { border:1px dashed #006600; color:#006600; font-size:12px; padding:2px 2px 2px 20px; width:280px; background:#99FF00 url(info.gif) no-repeat 2px center; } --></mce:style><style type="text/css" mce_bogus="1">.red { border:1px dashed #FF0000; color:#FF0000; font-size:12px; padding:2px 2px 2px 20px; width:280px; background:#FFCCFF url(error.gif) no-repeat 2px center; } .green { border:1px dashed #006600; color:#006600; font-size:12px; padding:2px 2px 2px 20px; width:280px; background:#99FF00 url(info.gif) no-repeat 2px center; }</style> </head> <body> <h1>使用jQuery实现AJAX帐号验证效果</h1> <form method="post" action=""> <table> <tr> <td><label for="username">帐号:</label></td> <td><input type="text" name="username" id="username" /></td> <td><div id="result"></div></td> </tr> </table> </form> </body> </html> register_handler.php <?php header("Content-type: text/html; charset=GBK"); if (isset($_REQUEST['username'])) { $username = $_REQUEST['username']; if (iconv("utf-8", "gb2312", $_REQUEST['username']) == "没有被占用") { echo "true"; exit(); } } echo "false"; ?>