日期:2014-05-16  浏览次数:20655 次

Prototype的Ajax支持使用Form.request方法

Form.request()方法实际上是Ajax.Request的封装,该方法会将所有的表单控件转换为请求参数,默认的向该表单的action指定的URL发送异步请求。

?

?

一个简单的用法例子:
<%@ 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 XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>使用Form.request</title>
		<meta name="author" content="Yeeku.H.Lee" />
		<meta name="website" content="http://www.crazyit.org" />
		<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
	</head>
	<body>
		<h3>
			请输入用户名、密码登录
		</h3>
		<form id="login" action="LoginServlet" method="post">
			用户名:
			<input name="user" type="text" />
			<br />
			密码:
			<input name="pass" type="text" />
			<br />
			<input value="登录" type="button" onclick="login();"/>
		</form>
		<script src="js/prototype-1.6.0.3.js" type="text/javascript"></script>
		<script type="text/javascript">
			//处理登录函数
			function login() {
				//使用Form的request发送异步请求
				$("login").request( {
					//指定回调函数
						onComplete : function(request) {
							alert(request.responseText);
						}
					});
			}
		</script>
	</body>
</html>
?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 LoginServlet extends HttpServlet {

	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.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String user = request.getParameter("user");
		String pass = request.getParameter("pass");
		
		PrintWriter out = response.getWriter();
		if (user.equals("libinxuan") && pass.equals("123456"))
		{
			out.println("登录成功!!");
		}else{
			out.println("登录失败!!");
		}
		
	}

}
?