用json + jQuery ajax实现页面实时数据刷新

 现在我想做的这个实例,最终实现的效果是:以一个文件构造json格式数据,通过jQuery ajax请求将其解析,然后填充Web页面内容,并结合实时数据显示;

    1. 构造json格式数据并不是一件容易的事情,对于不是熟手的人来说,这里我需要用到一些Asp.net方面的知识来构造我的json数据,以响应请求,如果不熟悉Asp.net将可跳过该环节,我将在本节最后贴出生成的数据源,由于我想利用现有的代码,并充分运用实战技巧,所以该段要用到一点其他东西,这里将综合个例,数据库中存在表:TabMer,记录系统的商品信息,如下图所示:

     

与一般性程序架构相同,我在程序中构造了一个与表相对应的实体类,实体类中的字段名就是表列名,实体类名称与表名相同,这里对该表的相关数据库访问代码及方法就省略了,至于字段的含义没必要了解的,然后,我建立了一个dataupdate.ashx文件,在asp.net中创建该类会创建一个public void ProcessRequest(HttpContext context)方法,该方法用于响应对dataupdate.ashx的请求,也就是说当请求.ashx文件时,都将执行public void ProcessRequest(HttpContext context)方法,context包含了HTTP 请求的所有 HTTP 特定的信息,比如请求的url参数信息,dataupdate.ashx类的ProcessRequest方法代码如下:

            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding.GetBytes("utf-8");
            int gid = Convert.ToInt32(context.Request.QueryString["gid"]);
            string json = "{rows:[";
            DataTable dt = BLL.OtherBLL.SelectDataByWhere("MCode,MName,MPrecision,MPDiff,MPrice,MAmount,MExchange,MMarginsType,MMargins,MPspan", "TabMer", " where MMGid = " + gid, " order by MOrderByid");
            foreach (DataRow item in dt.Rows)
            {
                decimal mprice = Convert.ToDecimal(item["MPrice"].ToString());
                decimal mdiff = Convert.ToDecimal(item["MPDiff"].ToString());
                int pre = Convert.ToInt16(item["MPrecision"].ToString());
                int mrtype = Convert.ToInt16(item["MMarginsType"].ToString());
                json += "{cell:[\"" + item["MCode"].ToString() + "\",\"";
                json += Convert.ToString(item["MName"]) + "\",\"";
                json += mprice.ToString("f" + pre) + "\",\"";
                json += (mprice + mdiff).ToString("f" + pre) + "\",\"";
                json += Convert.ToString(item["MAmount"]) + "\",\"";
                json += Convert.ToString(item["MExchange"]) + "\",\"";
                json += "定值" + "\",\"";
                json += (Convert.ToDecimal(item["MMargins"]) / (decimal)100).ToString("f" + pre) + "\",\"";
                json += Convert.ToDecimal(item["MPspan"]).ToString("f" + pre) + "\"]},";
            }
            json = json.TrimEnd(',');
            json += "]}";
            context.Response.Write(json);
            context.Response.Flush();
            context.Response.End();

该段代码将响应的数据格式定义为json,然后通过SelectDataByWhere方法查询表TabMer的数据,得到数据源之后封装成json格式的字符串,并将json数据作为响应流.
这里生成的json数据如下: 

 {rows:[

{cell:["SLV","君泰银[1*2500盎司]","222.00","222.00","2500","1.00000","定值","6000.00","1.00"]},

{cell:["gold","君泰金[1*100盎司]","33332.22","33332.22","100","1.00000","定值","12000.00","19.50"]}

]}

   2.使用jQuery ajax请求json数据,并填充到html页面

html引用了名为mermoni.js的js文件,该文件用于编写ajax请求,该页面的部分内容如下:

<table id="maincontent" width="100%" cellspacing="0" cellpadding="0" class="maincontent">
                            <tr>
                                <td class="totalhead" style="color: Yellow;">
                                    商品码
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    商品名
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    卖价
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    买价
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    每手的量
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    汇率
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    保证金类型
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    保证金明细
                                </td>
                                <td class="totalhead" style="color: Yellow;">
                                    跨度
                                </td>
                            </tr>
                        </table>

页面中包含id为maincontent的table元素,它将作为填充json数据的容器,
mermoni.js文件的源码如下:
$(function () {
    var initRecord = -1; var randomCode = 0; var oldrandomCode = 0;
    var initialfn = function () {
        randomCode = parseInt(Math.random() * 10000);
        oldrandomCode = parseInt(Math.random() * 10000);
        $.ajax({
            url: "../../ajaxhandler/dataupdate.ashx?" + randomCode + "=" + oldrandomCode,
            type: "get",
            dataType: "json",
            success: function (data, textStatus, XMLHttpRequest) {
                if (textStatus == "success") {
                    if (initRecord != -1) {
                        for (var k = 0; k < data.rows.length; k++) {
                            for (var h = 2; h < 4; h++) {
                                var slct = "#maincontent tr:not(:first):eq(" + k + ") td:eq(" + h + ")";
                                if (data.rows[k].cell[h].toString() != $(slct).text()) {
                                    if (parseFloat(data.rows[k].cell[h]) > parseFloat($(slct).text())) {
                                        $(slct).removeClass();
                                        $(slct).addClass("zhang");
                                    }
                                    else if (parseFloat(data.rows[k].cell[h]) < parseFloat($(slct).text())) {
                                        $(slct).removeClass();
                                        $(slct).addClass("die");
                                    }
                                    $(slct).text(data.rows[k].cell[h]);
                                }
                            }
                        }
                    } else {
                        $("#maincontent tr:not(:first)").remove();
                        for (var i = 0; i < data.rows.length; i++) {
                            var tr = $("<tr/>");
                            tr.hover(
                                function () { $(this).addClass("highlight"); },
                                function () { $(this).removeClass("highlight"); }
                            );
                            for (var j = 0; j < data.rows[i].cell.length; j++) {
                               $("<td/>").addClass("maincontenttd").text(data.rows[i].cell[j]).appendTo(tr);
                            }
                            $("#maincontent").append(tr);
                        }
                        initRecord = 1;
                    }
                }
            },
            error: function () { }
        });
        setTimeout(initialfn, 1500);
    }
    window.onload = initialfn;
});

 该段代码initRecord用于记录是否首次请求json数据,randomCode与oldrandomCode确保了每次ajax请求都不会被缓存,这里jQuery ajax中存在缓存的问题,可能使得请求得不到最新json数据,if (initRecord != -1) 结构块中的代码,表示若不是首次请求,则循环获得的json数据行,并通过jQuery选择html页面中相应的表格单元格数据与json存储的相应位置的数据进行对比,这里只选择了可能需要实时变动的第2到第4个单元格数据,由于是数字类型数据,若不相等[大于或小于],则表示有变动更改相应单元格文本并添加相应的类样式以提醒用户,else结构块的代码则显然是将json数据解析出来并在表格容易中添加新行,这里hover方法仅仅是jQuery的一个方法,仅作用于页面的美观.

好了:贴出最后效果图:


该实例能够根据卖价与买价的变动来实时展示数据,你会发现页面的加载和运行状态都很好,当然这里仅仅只有两行数据,当数据量较大的情况之下,页面的访问速度和性能将变得不那么可观,但是在web浏览器中,数据量较大显示出来时,用户在浏览器中肯定有一部分是看不到的,在这种情况下:对数据分页,是最好的选择,这里就不再继续,分页的方式我也有实现,也许以后我会继续介绍,将在此例的基础上添加分页实现,真正实现不受数据容量影响的实时页面数据展示.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值