有過網購的同學都知道,當我們在 網上買某一件東西的時候,如果我們把滑鼠放置到圖片的上方,那麼會彈出一個框框,介紹該產品的資訊,下面我們來類比一下這個功能
先寫一個shop.js
// JavaScript Documentvar 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}}
運行後的介面如下: