网格中的实时数据 - 更好的方法

本文介绍了网格中的实时数据 - 更好的方法的处理方法,对大家解决问题具有一定的参考价值

问题描述

在网格中显示实时数据(证券交易所、天气等)的更好方法是什么?
我用这个方法:

setInterval(function(){jQuery("#list1").trigger('reloadGrid');}, 5000);

解决方案

我觉得你的问题很有趣.我认为这个问题对于许多其他用户来说可能很有趣.所以我要 +1.

setInterval 的使用让我在常见的独立于浏览器的情况下找到了最好的方法.应该将 setInterval 的结果保存在一个变量中,以便能够使用 clearInterval 来停止它.

另一个小的改进是 [{current:true}] 的使用(参见 下载项目.

更新:我发布了 功能请求 以允许 beforeProcessing 通过返回来中断服务器响应的处理false 值.相应的更改已包含在 jqGrid 主代码中(请参阅此处).所以 jqGrid 的下一个版本将包含它.

What is for you the better approach for displaying real-time data (Stock Exchange, Weather, ...) in a grid ?
I use this method:

setInterval(function(){
      jQuery("#list1").trigger('reloadGrid');
}, 5000);

解决方案

I find your question very interesting. I think the question could be interesting for many other users. So +1 from me.

The usage of setInterval seams me the best way in common browser independent case. One should of cause save the result of setInterval in a variable to be able to use clearInterval to stop it.

One more small improvement would be the usage of [{current:true}] (see the answer for details) as the second parameter of trigger:

var $grid = jQuery("#list1"), timer;

timer = setInterval(function () {
    $grid.trigger('reloadGrid', [{current: true}]);
}, 5000);

It will save selection during the reloading of grid.

Many new web browsers support now WebSocket. So it would be better to use the way in case if the web browser supports it. In the way one can skip unneeded grid reloading in case if the data are not changed on server and prevent permanent pooling of the server.

One more common way seems to me also very interesting. If one would use some kind of timestamp of the last changes of the grid data one could verify whether the data are changed or not. One can either uses ETag or some general additional method on the server for the purpose.

The current success callback of jQuery.ajax which fill jqGrid allows you use to implement beforeProcessing callback to modify the server response, but it's not allows you to stop jqGrid refreshing based on jqXHR.satus value (it would be xhr.status in the current jqGrid code). Small modification of the line of the code of jqGrid would allows you to stop jqGrid refreshing in case of unchanged data on the server. One can either test textStatus (st in the current code of jqGrid) for "notmodified" or test jqXHR.satus (xhr.status in the current jqGrid code) for 304. It's important that to use the scenario you should use prmNames: { nd:null } option and set ETag and Cache-Control: private, max-age=0 (see here, here and here for additional information).

UPDATED: I tried to create the demo project based on my last suggestions and found out that it's not so easy as I described above. Nevertheless I made it working. The difficulty was because one can't see the 304 code from the server response inside of jQuery.ajax. The reason was the following place in the XMLHttpRequest specification

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content. The user agent must allow author request headers to override automatic cache validation (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through.

So one sees 200 OK status inside of success handler of $.ajax instead 304 Not Modified from the server response. It seems that XMLHttpRequest get back just full response from the cache inclusive all HTTP headers. So I decide to change the analyse of cached data just saving of ETag from the last HTTP response as new jqGrid parameter and test the ETag of the new response with the saved data.

I seen that you use PHP (which I don't use :-(). Nevertheless I can read and understand PHP code. I hope you can in the same way read C# code and understand the main idea. So you will be able to implement the same in PHP.

Now I describe what I did. First of all I modified the lines of jqGrid source code which use beforeProcessing callback from

if ($.isFunction(ts.p.beforeProcessing)) {
    ts.p.beforeProcessing.call(ts, data, st, xhr);
}

to

if ($.isFunction(ts.p.beforeProcessing)) {
    if (ts.p.beforeProcessing.call(ts, data, st, xhr) === false) {
        endReq();
        return;
    }
}

It will allows to return false from beforeProcessing to skip refreshing of data - to skip processing of data. The implementation of beforeProcessing which I used in the demo are based on the usage ETag:

beforeProcessing: function (data, status, jqXHR) {
    var currentETag = jqXHR.getResponseHeader("ETag"), $this = $(this),
        eTagOfGridData = $this.jqGrid('getGridParam', "eTagOfGridData");
    if (currentETag === eTagOfGridData) {
        $("#isProcessed").text("Processing skipped!!!");
        return false;
    }
    $this.jqGrid('setGridParam', { eTagOfGridData: currentETag });
    $("#isProcessed").text("Processed");
}

The line $("#isProcessed").text("Processed"); or the line $("#isProcessed").text("Processing skipped!!!"); set "Processed" or "Processing skipped!!!" text in the div which I used to indicate visually that the data from the server was used to fill the grid.

In the demo I display two grids with the same data. The fist grid I use for editing of data. The second grid pulls the data from the server every second. If the data are not changed on the server the HTTP traffic looks as following

HTTP Request:

GET http://localhost:34336/Home/DynamicGridData?search=false&rows=10&page=1&sidx=Id&sord=desc&filters= HTTP/1.1
X-Requested-With: XMLHttpRequest
Accept: application/json, text/javascript, */*; q=0.01
Referer: http://localhost:34336/
Accept-Language: de-DE
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; LEN2)
Host: localhost:34336
If-None-Match: D5k+rkf3T7SDQl8b4/Y1aQ==
Connection: Keep-Alive

HTTP Response:

HTTP/1.1 304 Not Modified
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 06 May 2012 19:44:36 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 2.0
Cache-Control: private, max-age=0
ETag: D5k+rkf3T7SDQl8b4/Y1aQ==
Connection: Close

So no data will be transferred from the server if the data are not changed. If the data are changed, the HTTP header will be started with HTTP/1.1 200 OK and contains ETag of new modified data together with the page of data itself.

One can refresh the data of the grid either manually using "Refresh" button of the navigator or uses "Start Autorefresh" button which will execute $grid1.trigger('reloadGrid', [{ current: true}]); every second. The page looks like

I marked the most important parts on the bottom of the page with the color boxes. If one loadui: "disable" option then one don't see any changes on the grid at all during the pulling of the server. If one commented the option that one will see "Loading..." div for very short time, but no grid contain will flicker.

After starting of "Autorefreshing" one will see mostly the picture like below

If one would change some row in the first grid, the second grid will be changed in a second and one will see "Processed" text which will be changed to "Processing skipped!!!" text in one more second.

The corresponding code (I used ASP.NET MVC) on the server side is mostly the following

public JsonResult DynamicGridData(string sidx, string sord, int page, int rows,
                                  bool search, string filters)
{
    Response.Cache.SetCacheability (HttpCacheability.ServerAndPrivate);
    Response.Cache.SetMaxAge (new TimeSpan (0));

    var serializer = new JavaScriptSerializer();
    ... - do all the work and fill object var result with the data

    // calculate MD5 from the returned data and use it as ETag
    var str = serializer.Serialize (result);
    byte[] inputBytes = Encoding.ASCII.GetBytes(str);
    byte[] hash = MD5.Create().ComputeHash(inputBytes);
    string newETag = Convert.ToBase64String (hash);
    Response.Cache.SetETag (newETag);
    // compare ETag of the data which already has the client with ETag of response
    string incomingEtag = Request.Headers["If-None-Match"];
    if (String.Compare (incomingEtag, newETag, StringComparison.Ordinal) == 0) {
        // we don't need return the data which the client already have
        Response.SuppressContent = true;
        Response.StatusCode = (int)HttpStatusCode.NotModified;
        return null;
    }

    return Json (result, JsonRequestBehavior.AllowGet);
}

I hope that the main idea of the code will be clear also for people which use not only ASP.NET MVC.

You can download the project here.

UPDATED: I posted the feature request to allow beforeProcessing to break processing of the server response by returning false value. The corresponding changes are already included (see here) in the main jqGrid code. So the next release of jqGrid will include it.

这篇关于网格中的实时数据 - 更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1173

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1071

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:809

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:900

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:931

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:879

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:865

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:834

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1734

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1309