与此不同,AJAX应用可以仅向服务器发送并取回必需的数据,它使用SOAP或其它一些基于XML的web service接口,并在客户端采用JavaScript处理来自服务器的响应。因为在服务器和浏览器之间交换的数据大量减少,结果我们就能看到响应更快的应用。同时很多的处理工作可以在发出请求的客户端机器上完成,所以Web服务器的处理时间也减少了。
不说那么多废话了,直接入题:
首先,写jsp页面:
<%@ taglib prefix="ww" uri="/webwork" %>
<%
String path=request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TimeCard Manager Platform</title>
<script src="<%=path%>/js/prototype.js"></script>
<script>
function getXML(){
//局部请求地址
var url="searchAction.action";
//获取用户当前输入的内容
var inputvalue=document.getElementById("itext").value;
//使用prototype函数构造xmlhttprequest对象
var myAjax = new Ajax.Request(
url,
{
//请求方法为post
method:'post',
//设置参数为 inputtext=inputtext
parameters:"inputtext="+inputvalue,
//设置回调函数
onComplete:showResponse,
//是否异步
asynchronous:true
}
);
}
function showResponse(xmlrequest){
//回调函数
var text = xmlrequest.responseText;
//将匹配的内容输出到 span 层
document.getElementById("projectspan").innerHTML=text;
// $("projectspan").innerHTML=xmlrequest.responseText;
}
</head>
<body>
Project manager:
<span id="projectspan" class="font_bluet"> <select
name="project.resource_id" id="prijectmanager">
<option value="-1"> Choose</option>
<option value="0" >aaaa</option>
<option value="1" >bbbb</option>
<option value="2" >cccc</option>
<option value="3" >dddd</option>
</select> </span>
<input name="text" type="text" id="itext" onKeyUp="getXML()" />
</body>
</html>
在XWORK.XML中加入下面的代码:
</action>
在action中:
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter out;
String inputtext = ServletActionContext.getRequest().getParameter("inputtext");
//根据输入框的内容到数据库查询符合条件项,返回
// List (resourcelist1)
//如果没有符合条件项,则查询所有列表,返回 List (resourcelist)
if(!resourcelist1.isEmpty() || resourcelist1.size()>0){
try {
out = ServletActionContext.getResponse().getWriter();
out.println("<select name='project.resource_id' id='prijectmanager' class='fram'>");
for(int i=0;i<resourcelist1.size();i++){
out.println("<option value=" + resourcelist1.get(i).getResourceId() + ">"
+ resourcelist1.get(i).getName() + "</option>");
}
out.println("</select>");
//输出缓存字符串
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
try {
out = ServletActionContext.getResponse().getWriter();
out.println("<select name='project.resource_id' id='prijectmanager' class='fram'>");
for(int i=0;i<resourcelist.size();i++){
out.println("<option value=" + resourcelist.get(i).getResourceId() + ">"
+ resourcelist.get(i).getName() + "</option>");
}
out.println("</select>No Information!");
//输出缓存字符串
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}