您的位置:首页 > 理论基础 > 计算机网络

Ajax实现提示功能

2012-07-31 18:34 316 查看
有过网购的同学都知道,当我们在 网上买某一件东西的时候,如果我们把鼠标放置到图片的上方,那么会弹出一个框框,介绍该产品的信息,下面我们来模拟一下这个功能

 

先写一个shop.js

 

// JavaScript Document
var xmlHttpRequest;
function createXmlHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");

}
else (window.XMLHttpRequest)
{
xmlHttpRequest=new XMLHttpRequest();
}

}

function over(index)
{
//alert("over执行");
x=event.clientX;
y=event.clientY;
createXmlHttpRequest();

xmlHttpRequest.onreadystatechange=processor;
xmlHttpRequest.open("GET","ShopServlet?index="+index,true);
xmlHttpRequest.send(null);

}

function processor()
{
//alert("1");
if(xmlHttpRequest.readyState==4)
{
//alert("2");
var result;
if(xmlHttpRequest.status==200)
{

//alert("2");
result=xmlHttpRequest.responseXML.getElementsByTagName("shop");

document.getElementById("tip").style.display="block";
document.getElementById("tip").style.top=y;
document.getElementById("tip").style.left=x+10;

document.getElementById("gname").innerHTML="商品名称:"+result[0].childNodes[0].firstChild.nodeValue;
document.getElementById("gprice").innerHTML="商品价格:"+result[0].childNodes[1].firstChild.nodeValue;
//alert("商品名称:"+result[0].childNodes[0].firstChild.nodeValue);

}
}
}

function out()
{
doucment.getElementById("tip").style.display="none";
}


然后写一个jsp页面,shop.jsp

 

body中的代码:

<h2>使用Ajax实现提示功能</h2>
<hr>
<a href="#"  onmouseover="over(0)"  onmouseout="out()">商品1</a>
<a href="#" onmouseover="over(1)"   onmouseout("out()")>商品2</a>
<a href="#" onmouseover="over(2)"   onmouseout("out()")>商品3</a>

<div id="tip" style="position: absolute;display: none;border: 1px;border-style: solid;">
<table id="tiptable" border="0" bgcolor="#ffffee">
<tr><td id="gname"></td></tr>
<tr><td id="gprice"></td></tr>
</table>


最后编写一个Servlet

public class ShopServlet extends HttpServlet
{

public void destroy()
{
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{

System.out.println("servlet执行");
response.setContentType("text/xml");
response.setCharacterEncoding("utf-8");
String[][]info={{"苹果","10"},{"香蕉","8"},{"梨子","4"}};
int index=Integer.valueOf(request.getParameter("index"));
PrintWriter pw=response.getWriter();
pw.println("<shop>");
pw.println("<name>"+info[index][0]+"</name>");
pw.println("<price>"+info[index][1]+"</price>");
pw.println("</shop>");

pw.flush();
pw.close();

}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException
{
// Put your code here
}

}


运行后的界面如下:



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息