weixin_33737134 2014-09-11 22:43 采纳率: 0%
浏览 58

使用Ajax和Perl更新HTML

I'm trying to update a div on my webpage using ajax & perl. This is what I have at the moment and it kind of works.

html

<h2 id="cpu">--</h2>

js/ajax call

   $.ajax({
      type: 'GET',
      url: '/cgi-bin/cpu.pl',
      async: true,
      success: function(data) {
        $('#cpu').html(data);
      } 
    });

perl

#!/usr/bin/perl

# Ref: Calculating CPU Usage from /proc/stat
# (http://colby.id.au/node/39)

use strict;
use warnings 'all';
use utf8;

use List::Util qw(sum);

$| = 1;

my ( $prev_idle, $prev_total ) = qw(0 0);
while () {
    open( STAT, '/proc/stat' ) or die "WTF: $!";
    while (<STAT>) {
        next unless m{^cpu\s+[0-9]+};
        my @cpu = split ' ', $_;
        shift @cpu;

        my $idle  = $cpu[3];
        my $total = sum(@cpu);

        my $diff_idle  = $idle - $prev_idle;
        my $diff_total = $total - $prev_total;
        my $diff_usage = 100 * ( $diff_total - $diff_idle ) / $diff_total;

        $prev_idle  = $idle;
        $prev_total = $total;

        print "Content-type: text/html 

";
        printf "%0.2f%%  ", $diff_usage;
    }
    close STAT;
}

This works partially because it does update the the h2 with a percentage but only once. I did have it where it said sleep 1; inside the loop and that worked great executing it from the command line but when I used it with ajax and I looked at the network, for cpu.pl it always said status pending and it never changed.

I'm not sure if I'm even going about this the correct way. So any help would be great, thanks.

  • 写回答

1条回答 默认 最新

  • weixin_33724046 2014-09-12 19:03
    关注

    It appears I was thinking of ajax the wrong way. Thanks charlietfl for the clarification. I'm still undecided about how I want to go about this. I was originally looking for a quick and dirty solution but I'm going to look into both jm666 & Ian Wise's suggestions.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?