bug^君 2015-10-06 02:55 采纳率: 25%
浏览 224

通过AJAX刷新表格

I have a task to provide users a status of a backend process that runs in our application. To display this status we have created a Status table in the database that lists the tasks that have completed, failed, or are in progress, like so:

enter image description here

To get the most current status of this table, I am calling an .ajax() method every 3 seconds by wrapping the call within a setInterval() method. The refresh works as expected and grabs the most current status of the program, however this was my first approach at the issue and feels a little brute force-ish. I'm wondering if a better way to accomplish this exists (i.e., a cross-browser solution that mimics a live news feed with it's own API). Any thoughts?

  • 写回答

1条回答 默认 最新

  • weixin_33738555 2015-10-06 02:57
    关注

    Try this http://www.w3schools.com/html/html5_serversentevents.asp

    sse is the best way to do it.

    Try this code

    <script>
    if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("demo_sse.php");
    source.onmessage = function(event) {
        //display data in event array.
    };
    } else {
    //Use your old interval if SSE not support in browser
    }
    </script>
    

    in your php code

    <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');//this is important
    
    $arr=['status'=>1,'data'=>$some_array];
    
    $retry="retry: 10000
    ";
    echo $.retry."data: ".json_encode($arr)."
    
    ";
    flush();
    ?>
    

    you need to add "data:" in the start of you display to SSE know that is your data and " " the end of data.

    and add retry, so it refresh every 10000=10 seconds

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致