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.

    评论

报告相同问题?