ajax长链接拉实现

     很多时候需要用在网页上实时显示数据,这个时候一般要用到长链接技术。最简单的实现就是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>



原文地址:https://www.cnblogs.com/alala666888/p/2349499.html