通过 ajax,javascript 可使用 javascript 的 xmlhttprequest 对象来直接与服务器进行通信。通过这个对象, javascript 可在不重载页面的情况与 web 服务器交换数据。
推荐课程:java教程。
ajax 在浏览器与 web 服务器之间使用异步数据传输(http 请求),这样就可使网页从服务器请求少量的信息,而不是整个页面。
实验中利用jsp+ajax来实现自动刷新页面,并读/写数据库中的数据。
下面介绍一下利用jsp+ajax来实现局部页面刷新的小例子:
处理ajax请求的jsp文件:ajax.jsp
<%@ page contenttype="text/html; charset=gb2312" %> <% //这是一个java程序//设置输出信息的格式及字符集response.setcontenttype("text/xml; charset=utf-8");response.setheader("cache-control","no-cache");out.println("<response>);for(int i=0;i<2;i++){ out.println("<name>+(int)(math.random()*10)+号传感器</name>);out.println(<count> +(int)(math.random()*100)+ </count>);}out.println(</response>);out.close();%>
发送ajax请求的jsp文件:zx.jsp
<head> <meta http-equiv=content-type content="text/html; charset=gb2312"> </head> <script language="javascript"> var xmlhttpreq; //创建xmlhttprequest对象 function createxmlhttprequest() { if(window.xmlhttprequest) { //mozilla 浏览器 xmlhttpreq = new xmlhttprequest(); } else if (window.activexobject) { // ie浏览器 try { xmlhttpreq = new activexobject(msxml2.xmlhttp); } catch (e) { try { xmlhttpreq = new activexobject(microsoft.xmlhttp); } catch (e) {} } } } //发送请求函数 function sendrequest() { createxmlhttprequest(); var url = ajax.jsp; xmlhttpreq.open(get, url, true); xmlhttpreq.onreadystatechange = processresponse;//指定响应函数 xmlhttpreq.send(null); // 发送请求 } // 处理返回信息函数 function processresponse() { if (xmlhttpreq.readystate == 4) { // 判断对象状态 if (xmlhttpreq.status == 200) { // 信息已经成功返回,开始处理信息 displayhot(); settimeout(sendrequest(), 1000); } else { //页面不正常 window.alert(您所请求的页面有异常。); } } } function displayhot() { var name = xmlhttpreq.responsexml.getelementsbytagname(name)[0].firstchild.nodevalue; var count = xmlhttpreq.responsexml.getelementsbytagname(count)[0].firstchild.nodevalue; document.getelementbyid(product).innerhtml = name; document.getelementbyid(count).innerhtml = count; } </script> <body onload =sendrequest()> <table style="border-collapse: collapse" bordercolor=#111111 cellspacing=0 cellpadding=0 width=200 bgcolor=#f5efe7 border=0> <tr> <td align=middle bgcolor=#dbc2b0 height=19 colspan="2"><b>无线传感网</b> </td> </tr> <tr> <td height="20"> 传感器:</td> <td height="20" id="product"> </td> </tr> <tr> <td height="20">传感器个数:</td> <td height="20" id="count"> </td> </tr> </body> </table>
效果如下(页面上的值自动变化):
局部刷新之后:
以上就是jsp怎么实现局部刷新的详细内容。
