引用此文,請注意這頁連結。
(一)在Eclipse中建立一個Java工程
工程名:ajax
然後在WebRoot下建立兩個Jsp,一個為validate.jsp,它的作用是進行輸入,提交;另一個為date.jsp它就是對輸入值進行驗證。
(二) validate.jsp 代碼
<%@ page contentType="text/html; charset=GBK"%>
<html>
<head>
<title>資料驗證</title>
<script type="text/javascript" >
<!---
/*
這個 button中的onClick()函數
作用:(1)進行輸入框中的空值判定
(2)當不為空白時,去調用可執行非同步作業的函數
*/
function userCheck()
{
//下面取元素並沒有用id這樣的屬性來取對應的值
var f=document.form1; //取出 form1所對應的元素
var username=f.username.value; //取出 from1下面username的值
alert('此元素的類型:'+f.username.type+' '+"/r/n此元素的名稱:"+f.username.name);
if(username=="")
{
//window.alert("使用者不可為空!"); 這兩種都可以
alert("使用者不可為空!");
f.username.focus(); //獲得焦點
return false;
}else
{
//如果填寫的不為空白值的操作
send_request("date.jsp?username="+username);
}
}
var http_request=false;
//進行ajax的處理函數
function send_request(url)
{
//擷取要調用的URL,傳入函數
http_request=false;
if(window.XMLHttpRequest)
{
//Mozilla瀏覽器 或是非IE瀏覽器
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType)
{
http_request.overrideMimeType("text/html");
}
}else if(window.ActiveXObject)
{
//IE瀏覽器
try {
http_request=new ActiveXObject("Msxml2.XMLHTTP"); //Internet Explorer 中安裝的 JavaScript 技術版本不同,MSXML 實際上有兩種不同的版本,
}catch(e)
{
try
{
http_request=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
//當不能建立 XMLHttpRequest時
if(!http_request)
{
window.alert("不能建立XMLHttpRequest對象執行個體");
return false;
}
//processRequest雖然是一個函數,但在這不能加括弧也不能給參數,更不能把下此函數的函數放在這句話的後面
http_request.onreadystatechange=processRequest;
//確定發送請求的方式和URL以及是否同步執行下段代碼
//第一參數為傳輸的方式get post head 第二個參數為:要互動的URL;第三個參數:是否為非同步傳輸
http_request.open("get",url,true);
http_request.send(null);
}
//處理返回資訊的函數
function processRequest()
{
//代表從伺服器中取的所有的值
if(http_request.readyState==4)
{
if (http_request.status == 200) { // 資訊已經成功返回,開始處理資訊
//將輸回的訊息當字串處理,還有responseXML(將輸回來的訊息當文檔使用,可用DOM處理)
alert(http_request.responseText);
}else{
alert("您所請求的頁面有異常。");
}
}
}
-->
</script>
</head>
<body>
<center>
<form name="form1" action="" method="post">
使用者名稱:<input type="text" name="username" value="" > <br>
<input type="button" name="check" value="唯一性檢查" onClick="userCheck()">
<input type="submit" name="submit" value="提交">
</form>
</center>
</body>
</html>
注意:括弧要匹配,不然在<input type="button">這一行總會報缺少對象。
參考:XMLHttpRequest與瀏覽器之別 http://www.cnbruce.com/blog/showlog.asp?log_id=987&cat_id=34
(三)date.jsp 代碼
<%@ page contentType="text/html; charset=GBK"%>
<%
String username = request.getParameter("username");
if ("liusong".equals(username.trim()))
{
out.println("使用者名稱已經被注刪,請更換一個使用者名稱");
} else
{
out.println("使用者尚未被使用,您可以繼續");
}
%>
(三)運行
A::當什麼出不輸入時
B:輸入不存的使用者時
C:當輸入的使用者存在時