简单请求:先上效果图(1)
所谓简单请求,指不包含任何参数的请求。这种请求通常用于自动刷新的应用,例如证券交易所的实时信息发送。
对于简单请求,因为无需发送请求参数,因此采用GET或者POST没有太大区别。
实现代码如下:
<body> mysql的虚拟股票价格:<div id="mysql" style="color:red;font-weight:bold;"></div> tomcat的虚拟股票价格:<div id="tomcat" style="color:red;font-weight:bold;"></div> jetty的虚拟股票价格:<div id="jetty" style="color:red;font-weight:bold;"></div> <script type="text/javascript"> //XMLHttpRequest对象 var xmlrequest; //创建XMLHttpRequest对象的初始化函数 function createXMLHttpRequest() { if(window.XMLHttpRequest) { //DOM 2浏览器 xmlrequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE浏览器 try { xmlrequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlrequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } } //用于发送简单请求的函数 function getPrice() { //初始化XMLHttpRequest对象 createXMLHttpRequest(); var uri = "second.jsp"; //打开与服务器的连接 xmlrequest.open("POST", uri, true); //指定当XMLHttpRequest状态改变时的事件处理函数 xmlrequest.onreadystatechange = processResponse; //发送请求 xmlrequest.send(null); } //当XMLHttpRequest状态改变时,该函数将被触发 function processResponse() { if(xmlrequest.readyState == 4) { if(xmlrequest.status == 200) { //将服务器响应以$符号分割成一个字符串数组 var prices = xmlrequest.responseText.split("$"); //将服务器的响应通过页面显示。 document.getElementById("mysql").innerHTML=prices[0]; document.getElementById("tomcat").innerHTML=prices[1]; document.getElementById("jetty").innerHTML=prices[2]; //设置1秒钟后再次发送请求,定时器,每秒更新 setTimeout("getPrice()", 1000); } } } //指定页面加载完成后指定getPrice()函数 document.body.onload = getPrice; </script> </body>
first.html中用ajax向指定url发送空参数,即second.jsp。从jsp中返回“数$数$数”,故在first.html中事件处理函数
processResponse时按$分割返回的字符串,并把3个随机数赋到3个div中
下面是second.jsp的代码
<%@ page contentType="text/html; charset=GBK" language="java"%> <%@ page import="java.util.Random"%> <% //创建伪随机器,以系统时间作为伪随机器的种子 Random rand = new Random(System.currentTimeMillis()); //生成三个伪随机数字,并以$符号隔开后发送到客户端 out.println(rand.nextInt(10) + "$" + rand.nextInt(10) + "$" + rand.nextInt(10)); %>