如何使用Ajax(XMLHttpRequest)发送带参数的请求,以及如何在Servlet中获取请求中的参数

其实这样设计的初衷是为了在客户端发出请求前,对要发送的数据进行预处理。比如用户密码的加密操作等等。

var xmlhttp;//设置全局变量

function login() {
        //这里为了简化代码,没有附上密码加密的代码
	var params = "username=" + document.getElementById("username").value
			+ "&password=" + document.getElementById("password").value;
	sendRequest(
			"POST",
			"login",
			true,
			params,
			function() {
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					document.getElementById("message").innerHTML = xmlhttp.responseText;
				}
			});
}

function sendRequest(method, url, isAsyns, params, action) {
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open(method, url, isAsyns);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//这行代码很关键,用来把字符串类型的参数序列化成Form Data
	xmlhttp.send(params);
	xmlhttp.onreadystatechange = action;
}

public void doPost(HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		......
	}


你可能感兴趣的:(Ajax,Servlet)