jsp 通过 Ajax 和servlet之间的连接及数据传递示例

效果图:很基本的例子,不过刚开始把第三步open()连接中url 写错了,老是访问不到,如果出现相同的问题,可以再js部分第二步中通过alert(“xmlReq.readystate=”+xmlReq+"   "+"xmlReq.status="+xmlReq.status);来调试错误地方

jsp 通过 Ajax 和servlet之间的连接及数据传递示例_第1张图片

jsp代码:

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






Register











	
用户注册
用户名:
密  码:
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 {
	}

}
 
  

 
 

你可能感兴趣的:(Ajax)