引荐课程: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怎样完成部分革新的细致内容,更多请关注ki4网别的相干文章!