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

本文介绍如何利用Prototype框架中的Form.request方法实现表单的异步提交,并通过一个具体的登录示例展示了从HTML表单到后端Servlet的完整过程。

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("登录失败!!");
		}
		
	}

}
 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值