Ajax PRG
Ajax PRG
*; public class countservlet extends HttpServlet { private static int visits=0; public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { visits++; res.setContentType("text/html"); PrintWriter srout=res.getWriter(); srout.println("<html><head><title> Example program for Ajax</title><script type='text/javascript' src='/countupdate.js'></script>"+ "</head><body onload='init()'><p>Welcome to the world :\n Number of visits:</p><p id='visits'>0 </p></body></html>"); srout.close(); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("application/xml"); PrintWriter srout=res.getWriter(); srout.println("<?xml version='1.0' ?> <count>"+visits+"</count>"); srout.close(); } }
//countupdate.js function init() { window.setInterval("getvisits()",300); return; } function getvisits() { var con=new XMLHttpRequest(); if(con) { con.open("POST","/countservlet",true); con.onreadystatechange=function update(){updatevisits(con);} con.send(""); } return; } function updatevisits(con) { if(con.readyState==4 && con.status==200) { visits=document.getElementById("visits"); var count=con.responseXML.documentElement; visits.childNodes[0].data=count.childNodes[0].data; } return; }