Ajax無重新整理驗證使用者名稱是否被註冊了
DOM版,此代碼僅支援IE瀏覽器
<!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> <title></title> <script type="text/javascript"> function checkUser() { var text1 = document.getElementById("Text1").value;
if(text1!=""){ var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); if(!xmlhttp){ alert("ajax錯誤"); return false; } xmlhttp.open("POST", "CheckUserName.ashx?username=" + text1 + "&t=" + new Date(), "false"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { // alert(xmlhttp.responseText); if (xmlhttp.responseText == "ok") { document.getElementById("sp1").innerHTML = "<font color=green>恭喜使用者名稱'" + text1 + "'可以使用</font>"; } else if (xmlhttp.responseText == "error") { document.getElementById("sp1").innerHTML = "<font color=red>使用者名稱'" + text1 + "'已經被註冊了</font>"; } else { alert("ajax返回錯誤"); } } else { alert("ajax伺服器返回錯誤"); } } } xmlhttp.send(); } } </script></head><body> 使用者名稱:<input id="Text1" type="text" onblur="return checkUser()" /><span id="sp1"></span></body></html>
JQuery版,此代碼相容絕大部分瀏覽器.
<!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> <title></title> <script src="../js/jquery-1.4.2.js" type="text/javascript"></script> <script type="text/javascript"> function checkUser() { var username = $("#Text1").val(); if (username != "") { $.post("CheckUserName.ashx", { "username": username }, function(data, status) {//jQuery封裝的ajax post方法,第一個參數為post頁面,第二個為參數數組,第三個為接受結果匿名函數 if (status == "success") {//返回成功 if (data == "ok") {//值為ok $("#sp1").html("<font color=green>恭喜使用者名稱'" + username + "'可以使用</font>") } else if (data == "error") {//值為error $("#sp1").html("<font color=red>使用者名稱'" + username + "'已經被註冊了</font>") } else { alert("return error"); } } else { alert("ajax error"); } }); } } </script></head><body> 使用者名稱:<input id="Text1" type="text" onblur="return checkUser()" /><span id="sp1"></span></body></html>
伺服器處理常式:CheckUserName.ashx
<%@ WebHandler Language="C#" Class="CheckUserName" %>using System;using System.Web;public class CheckUserName : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string us=context.Request["username"]; jiang_Db newdb = new jiang_Db(); bool hasname = newdb.ExecSql_Bool("select COUNT(*) from [user] where [user_name]='"+us+"'"); if (hasname) { context.Response.Write("error"); } else { context.Response.Write("ok"); } } public bool IsReusable { get { return false; } }}