簡單請求:先上效果圖(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)); %>