1. 程式人生 > >jsp 通過 Ajax 和servlet之間的連線及資料傳遞示例

jsp 通過 Ajax 和servlet之間的連線及資料傳遞示例

效果圖:很基本的例子,不過剛開始把第三步open()連線中url 寫錯了,老是訪問不到,如果出現相同的問題,可以再js部分第二步中通過alert(“xmlReq.readystate=”+xmlReq+"   "+"xmlReq.status="+xmlReq.status);來除錯錯誤地方

jsp程式碼:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>Register</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<script type="text/javascript" src="./register/Register.js"></script>
</head>

<body>
	<form action="" enctype="application/x-www-form-urlencoded">
		<table border="1">
			<tr>
				<td colspan="2" align="center"><Strong>使用者註冊</Strong>
				</td>
			</tr>
			<tr>
				<td>使用者名稱:</td>
				<td><input type="text" id="username">
					<div id="divcheck"></div>
			</tr>
			<tr>
				<td>密  碼:</td>
				<td><input type="password" id="password"></td>
			</tr>
			<tr>
				<td><input type="button" value="驗證" id="checkusername">
				</td>
				<td align="center"><input type="reset" value="重置">
				</td>
			</tr>
			<!-- <tr>
				<td><a href="javascript:;" onclick="find()" id="1"
					value="100">平臺簡介</a></td>
				<td><a>開放業務</a>
				</td>
			</tr> -->
		</table>
	</form>
</body>
</html>
js程式碼
//建立XMLHttpRequest 物件的函式
function ajaxFunction() {
	var xmlHttp;
	try {// Firefox,Opera,Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}

	}
	return xmlHttp;
}

window.onload = function() {
	document.getElementById("checkusername").onclick = function() {
		var username = document.getElementById("username").value;
		// 1建立xmlHTTP物件
		var xmlReq = ajaxFunction();
		/**
		 * 2、處理伺服器端的響應 readyState的值為4代表響應完成 status屬性:200代表一切正常;304代表原始檔沒有別修改
		 * 404代表找不到頁面;403禁止訪問; 500 內部伺服器錯誤
		 * 
		 */
		xmlReq.onreadystatechange = function() {
			if (xmlReq.readyState == 4) {
				if (xmlReq.status == 200 || xmlReq.status == 304) {
					var data = xmlReq.responseText;
					document.getElementById("divcheck").innerHTML = data;
				}
			}
		};

		// 3、開啟和伺服器端的連線 如果是get方法,則改為get並且刪掉第二條語句
		var url = "./servlet/registServlet";
		xmlReq.open("post", url, true);
		xmlReq.setRequestHeader("Content-Type",
				"application/x-www-form-urlencoded");
		// 4、get 方法不會接受到,這裡只適合於post方法傳遞引數
		xmlReq.send("username=" + username);
	};
};
servlet程式碼:
package cn.servlet;

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 registServlet extends HttpServlet {

	private static final long serialVersionUID = -2968705132907930725L;

	public registServlet() {
		super();
	}

	public void destroy() {
		super.destroy();

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		if ("admin".equals(username)) {
			out.println("使用者名稱已存在~");
		} else {
			out.println("使用者名稱可用~");
		}
	}

	public void init() throws ServletException {
	}

}