详细解决方案
Prototype的Ajax支持应用Ajax.Request类
热度:220 发布时间:2012-10-31 14:37:31.0
Prototype的Ajax支持使用Ajax.Request类
我们只要简单的创建一个Ajax.Request对象,就可以完成异步请求的放送
<%@ 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>输入提示示范</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>
<div style="width: 280px; font-size: 9pt">
输入apple、banana、peach可看到明显效果:
</div>
<br />
<!-- 当鼠标移开的时候执行hide方法,隐藏起来 -->
<input id="favorite" name="favorite" type="text"
onblur="$('tips').hide();" />
<div id="tips"
style="width: 160px; border: 1px solid menu; background-color: #ffffcc; display: none"></div>
<script src="js/prototype-1.6.0.3.js" type="text/javascript"></script>
<script type="text/javascript">
//监控目标文本框输入文字发生改变的函数
function searchFruit() {
//请求的地址
var url = 'TipServlet';
//将favorite表单域的值转换为请求参数
var params = Form.Element.serialize('favorite');
//创建Ajax.Request对象,对应于发送请求
var myAjax = new Ajax.Request(url, {
//请求方式:POST
method : 'post',
//请求参数
parameters : params,
//指定回调函数
onComplete : showResponse,
//是否异步发送请求
asynchronous : true
});
}
//定义回调函数
function showResponse(request) {
//在提示tip元素中输出服务器的响应
$('tips').innerHTML = request.responseText;
//显示提示tip对象
$('tips').show();
}
//为favorite表单域绑定事件处理函数
new Form.Element.Observer("favorite", 0.5, searchFruit);
</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 TipServlet 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");
//获取请求参数favorite
String hdchar = request.getParameter("favorite");
System.out.println(hdchar);
PrintWriter out = response.getWriter();
//如果请求参数是apple的前几个字符,则输出apple
if ("apple".startsWith(hdchar))
{
out.println("apple");
}
//如果请求参数是banana的前几个字符,则输出banana
else if("banana".startsWith(hdchar))
{
out.println("banana");
}
//如果请求参数是peach的前几个字符,则输出peach
else if("peach".startsWith(hdchar))
{
out.println("peach");
}
//否则将输出other fruit
else
{
out.println("other fruit");
}
}
}
?