很多论坛都有进入后,弹出提示,说有多少封邮件没有看,或者是一个oa系统,进入后,提示有多少个任务没有做。每隔一段时间会提示一次,但是如何实现呢。其实,利用jquery的话,会比较简单,核心元素就是json格式解析和setInterval()函数。下面一起来实现:
首先,我们default.aspx的页面如下所示:
代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 runat="server">
<title>服务器轮询</title>
<link href="Content/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />
<link href="Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="js/src/grid.base.js" type="text/javascript"></script>
<script type="text/javascript">
function showUnreadNews()
{
$(document).ready(function() {
$.ajax({
type: "GET",
url: "Result.ashx",
dataType: "json",
success: function(msg) {
//alert(msg);
$.each(msg, function(id, title) {
$("#news").append("<a href=detailnews.aspx?id=" + id + ">" + title + "</a><br>");
});
}
});
});
}
setInterval('showUnreadNews()',5000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="news">
</div>
</form>
</body>
</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 runat="server">
<title>服务器轮询</title>
<link href="Content/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />
<link href="Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="js/src/grid.base.js" type="text/javascript"></script>
<script type="text/javascript">
function showUnreadNews()
{
$(document).ready(function() {
$.ajax({
type: "GET",
url: "Result.ashx",
dataType: "json",
success: function(msg) {
//alert(msg);
$.each(msg, function(id, title) {
$("#news").append("<a href=detailnews.aspx?id=" + id + ">" + title + "</a><br>");
});
}
});
});
}
setInterval('showUnreadNews()',5000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="news">
</div>
</form>
</body>
</html>
上面代码主要利用ajax函数向Result.ashx页面发出ajax请求,然后由Result.ashx这个页面返回json数据,并进行解析,最后利用setInterval()函数实现轮询效果,具体的Result.ashx页面代码如下:
代码
<%@ WebHandler Language="C#" Class="Result" %>
using System;
using System.Web;
using System.Text;
using System.Data.SQLite;
using System.Data;
public class Result : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string sql = "select * from Content where NewsFlag=0";
DataTable dt = new DataTable();
using (SQLiteConnection conn = new SQLiteConnection(InitSQLite().Connection))
{
SQLiteDataAdapter sda = new SQLiteDataAdapter(sql, conn);
sda.Fill(dt);
}
string jsonStr = GetJson(dt);
context.Response.ContentType = "text/json";
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
context.Response.AddHeader("pragma", "no-cache");
context.Response.AddHeader("cache-control", "");
context.Response.CacheControl = "no-cache";
context.Response.Write(jsonStr);
}
public static string GetJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append( dt.Rows[i]["NewsID"].ToString() + ":" +"\""+ dt.Rows[i]["NewsTitle"].ToString()+"\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
public Sqlite InitSQLite()
{
Sqlite _sqLite = new Sqlite();
_sqLite.ConnetStringBuilder.DataSource = AppDomain.CurrentDomain.BaseDirectory + "News.db3";
_sqLite.ConnetStringBuilder.Pooling = true;
_sqLite.ConnetStringBuilder.FailIfMissing = true;
_sqLite.ConnetStringBuilder.UseUTF16Encoding = true;
return _sqLite;
}
public bool IsReusable {
get {
return false;
}
}
}
using System;
using System.Web;
using System.Text;
using System.Data.SQLite;
using System.Data;
public class Result : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string sql = "select * from Content where NewsFlag=0";
DataTable dt = new DataTable();
using (SQLiteConnection conn = new SQLiteConnection(InitSQLite().Connection))
{
SQLiteDataAdapter sda = new SQLiteDataAdapter(sql, conn);
sda.Fill(dt);
}
string jsonStr = GetJson(dt);
context.Response.ContentType = "text/json";
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
context.Response.AddHeader("pragma", "no-cache");
context.Response.AddHeader("cache-control", "");
context.Response.CacheControl = "no-cache";
context.Response.Write(jsonStr);
}
public static string GetJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append( dt.Rows[i]["NewsID"].ToString() + ":" +"\""+ dt.Rows[i]["NewsTitle"].ToString()+"\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
public Sqlite InitSQLite()
{
Sqlite _sqLite = new Sqlite();
_sqLite.ConnetStringBuilder.DataSource = AppDomain.CurrentDomain.BaseDirectory + "News.db3";
_sqLite.ConnetStringBuilder.Pooling = true;
_sqLite.ConnetStringBuilder.FailIfMissing = true;
_sqLite.ConnetStringBuilder.UseUTF16Encoding = true;
return _sqLite;
}
public bool IsReusable {
get {
return false;
}
}
}
数据库使用的是sqlite,具体使用方式请自查。这个处理文件中,最重要的是由datatable数据生成符合格式的json数据。
这样,系统最终就实现了,每隔5S钟,首页会向服务器轮询一次数据,以便获得最新的数据。