今天無意間看見一個這樣的AJAX例子,覺得很有價值,于是便記錄了下來,以供以后參考。
原文地址:
http://hi.baidu.com/casa2/blog/item/7a6bc1c684e81c1f9d163df5.html
本例將在頁面的參數以Get和POST兩種方式傳遞到服務器,并回顯到頁面;
本例共包括兩個主要文件getAndPostExample.html和GetAndPostExample.java以及一個配置文件web.xml
建立文件的步驟:
1.在Eclipse新建一個web project-->ajax1
2.在ajax1里面新建一個getAndPostExample.html
3.在ajax1里面新建一個servlet-->GetAndPostExample.java
getAndPostExample.html如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>getAndPostExamplel.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
var xmlHttp;
//創建XMLhttpRequest對象
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
//生成傳遞到服務器的參數查詢串,參數值由頁面表單填寫得到
function createQueryString() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var birthday = document.getElementById("birthday").value;
var queryString = "firstName=" + firstName + "&middleName=" + middleName
+ "&birthday=" + birthday;
return queryString;
}
//點擊按鈕響應的Get方法主函數
//Get方法把參數值以名=值方式在xmlHttp.open("GET", queryString, true)中傳遞,queryString的形式為URL?參數名=值&參數名=值...;而xmlHttp.send(null);
function doRequestUsingGET() {
createXMLHttpRequest();//第一步:創建XMLHttpRequest對象
var queryString = "GetAndPostExample?";
queryString = queryString + createQueryString()
+ "&timeStamp=" + new Date().getTime();//第二步:定義傳遞的參數值字符串
xmlHttp.open("GET", queryString, true);//第三步:建立與服務器的請求
xmlHttp.onreadystatechange = handleStateChange;//第四步:監聽狀態-->轉到監聽狀態函數
xmlHttp.send(null);//第五步:發送請求,并且立即返回
}
//點擊按鈕響應的POST方法主函數
//POST方法把參數值以名=值方式在xmlHttp.send(queryString)中傳遞,queryString的形式為參數名=值&參數名=值...;
function doRequestUsingPOST() {
createXMLHttpRequest();//第一步:創建XMLHttpRequest對象
var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
var queryString = createQueryString();//第二步:定義傳遞的參數值字符串
xmlHttp.open("POST", url, true);//第三步:建立與服務器的請求
xmlHttp.onreadystatechange = handleStateChange;//第四步:監聽狀態-->轉到監聽狀態函數
xmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;");
xmlHttp.send(queryString);//第五步:發送請求,并且立即返回
}
//監聽狀態函數
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();//-->轉到函數parseResults輸出從服務器返的值
}
}
}
//在頁面顯示從服務器傳來的結果
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);//
responseDiv.appendChild(responseText);
}
</script>
</head>
<body>
<h1>Enter your first name, middle name, and birthday:</h1>
<table>
<tbody>
<tr>
<td>First name:</td>
<td><input type="text" id="firstName"/>
</tr>
<tr>
<td>Middle name:</td>
<td><input type="text" id="middleName"/>
</tr>
<tr>
<td>Birthday:</td>
<td><input type="text" id="birthday"/>
</tr>
</tbody>
</table>
<form action="#">
<input type="button" value="Send parameters using GET"
onclick="doRequestUsingGET();"/><!--調用Get方法主函數-->
<br/><br/>
<input type="button" value="Send parameters using POST"
onclick="doRequestUsingPOST();"/><!--調用POST方法主函數-->
</form>
<br/>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>
GetAndPostExample.java 如下
package com.ajax1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetAndPostExample extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response, String method)
throws ServletException, IOException {
//把響應內容類型設置為 text/xml
response.setContentType("text/xml");
//得到用戶參數值
String firstName = request.getParameter("firstName");
String middleName = request.getParameter("middleName");
String birthday = request.getParameter("birthday");
//生成包含用戶參數值的返回字符串
String responseText = "Hello " + firstName + " " + middleName
+ ". Your birthday is " + birthday + "."
+ " [Method: " + method + "]";
//寫回瀏覽器
PrintWriter out = response.getWriter();
out.println(responseText);
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get主函數調用processRequest,完成Get方法的參數接受,返回的過程
processRequest(request, response, "GET");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//POST主函數調用processRequest,完成POST方法的參數接受,返回的過程
processRequest(request, response, "POST");
}
}
web.xml 如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>GetAndPostExample</servlet-name>
<servlet-class>com.ajax1.GetAndPostExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAndPostExample</servlet-name>
<url-pattern>/GetAndPostExample</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在這個簡單的AJAX的例子里getAndPostExaple.html負責表單參數的輸入和傳遞,而servlet GetAndPostExample.java負責在服務器端接受參數。參數傳遞時加的時間戳是保證URL的唯一性。
posted on 2008-04-21 12:22
biiau 閱讀(5846)
評論(8) 編輯 收藏