客户端:
<script language="javascript">
var xmlHttp;
var x,y;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
function over(index){
x = event.clientX;
y = event.clientY;
createXMLHttpRequest();
xmlHttp.onreadystatechange=processor;
xmlHttp.open("GET","servlet/CreateTip?index="+index);
xmlHttp.send(null);
}
function processor(){
var result;
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
result = xmlHttp.responseXML.getElementsByTagName("shop");
document.all.tip.style.display="block";
document.all.tip.style.top=y;
document.all.tip.style.left=x+100;
document.all.photo.src=result[0].childNodes[2].firstChild.nodeValue;
document.all.tipTable.rows[1].cells[0].innerHTML="商品名称:"+result[0].childNodes[0].firstChild.nodeValue;
document.all.tipTable.rows[2].cells[0].innerHTML="商品价格:"+result[0].childNodes[1].firstChild.nodeValue;
}
}
}
function out(){
document.all.tip.style.display="none";
}
</script>
<body>
This is my HTML page. <br>
<h2>工具提示</h2><br>
<br>
<a href="servlet/CreateTip?index=1">OK let's go to the servlet</a>
<br><br>
<a href="#" οnmοuseοver="over(0)" οnmοuseοut="out()">商品一</a><br><br>
<a href="#" οnmοuseοver="over(1)" οnmοuseοut="out()">商品二</a><br><br>
<a href="#" οnmοuseοver="over(2)" οnmοuseοut="out()">商品三</a><br><br>
<div id="tip" style="position:absolute;display:none;border:1px;border-style:solid ">
<table id="tipTable" border="0" bgcolor="#ffffee">
<tr align="center">
<td><img id="photo" src="" height="80" width="80"/></td>
</tr>
<tr><td></td></tr>
<tr><td></td></tr>
<br>
</table>
</div>
</body>
服务器端:
public class CreateTip 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 {
//虚拟一个商品列表
String[][] shop ={{"商品一","90","photo/photo1.jpg"},
{"商品二","190","photo/photo2.jpg"},
{"商品三","290","photo/photo3.jpg"} };
//获得客户端提交的参数
int index =Integer.parseInt(request.getParameter("index"));
response.setContentType("text/xml");
//由于想当然的写成了response.setContentType("text/html");造成了很大的失误
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
//以XML文档形式返回给客户端
out.println("<shop>");
out.println("<name>"+shop[index][0]+"</name>");
out.println("<price>"+shop[index][1]+"</price>");
out.println("<photo>"+shop[index][2]+"</photo>");
out.println("</shop>");
out.flush();
out.close();
}
}