java網(wǎng)絡(luò)編程-Ajax+servlet實(shí)例
Ajax異步請(qǐng)求,servlet產(chǎn)生隨機(jī)數(shù)據(jù),Html頁(yè)面無(wú)刷新顯示。 一、ajaxServlet.java package com; 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; import java.util.Random; public class ajaxServlet extends HttpServlet{
|
二,、testajax.html
function getResult(){ var url = "/Tajax/AajaxServlet?action=send"; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); }else if (window.ActiveXObject){ req = new ActiveXObject("Microsoft.XMLHTTP"); } if(req){ req.open("GET",url, true); req.onreadystatechange = complete; req.send(null); } } /*分析返回的文本文檔*/ function complete(){ if (req.readyState == 4) { if (req.status == 200) { // alert(req.responseText); var strResult = unescape(req.responseText); var arrResult = strResult.split("@@@"); RemoveRow(); //刪除以前的數(shù)據(jù). num1 = arrResult[0]; //字段num1的值 num2 = arrResult[1]; //字段num2的值 num3 = arrResult[2]; num4 = arrResult[3]; row1= tb.insertRow(); cell1 = row1.insertCell(); cell1.innerText = num1; cell2 = row1.insertCell(); cell2.innerText = num2; row2= tb.insertRow(); cell3 = row2.insertCell(); cell3.innerText = num3; cell4 = row2.insertCell(); cell4.innerText = num4; } else { alert(‘There was a problem with the request.‘); } } } function RemoveRow(){//保留第一行表頭,其余數(shù)據(jù)均刪除. var iRows = tb.rows.length; for(var i=0;i< iRows-1;i++){ tb.deleteRow(1); } } function MyShow(){//2秒自動(dòng)刷新一次,2秒取得一次數(shù)據(jù). timer = window.setInterval("getResult()",2000); } </script>
<body onload="MyShow()"> <form> </body> 三、web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java./xml/ns/j2ee" <display-name>Welcome to Tomcat</display-name> <servlet>
運(yùn)行圖: |
|