很多時候需要用在網頁上即時顯示資料,這個時候一般要用到長連結技術。最簡單的實現就是ajax輪詢,也就是拉的方式。 下面是一個簡單的例子:在網頁上即時顯示伺服器時間。
後端WebService代碼:
/// <summary>
/// ServerTime 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class ServerTime : System.Web.Services.WebService
{
/// <summary>
/// 擷取伺服器端時間
/// </summary>
/// <returns></returns>
[WebMethod]
[ScriptMethod(UseHttpGet=true, ResponseFormat=ResponseFormat.Json)]
public string GetTime()
{
return DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");
}
}
前段html代碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js" ></script>
<script type="text/javascript">
function callWebService(url, param, handler) {
$.ajax({
url: url,
data: param,
type: "get",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (p) {
handler(p.d);
}
});
};
</script>
</head>
<body>
<script language="javascript" type="text/javascript">
//輪詢重新整理伺服器時間
setInterval(showTime, 1000);
function showTime() {
callWebService("ServerTime.asmx/GetTime", null, function (data) {
$("#serverTime").html(data);
});
}
</script>
<div id="serverTime"></div>
</body>
</html>