本文介绍了谷歌可视化仪表动态更新使用jQuery阿贾克斯 - 从JSON供稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不从希望看到一个LAMP服务器上的SYSINFO数据的图形重新presentation客户端的REQ。对于我们这些谁preFER视觉有。

我发现谷歌图表仪表和他们的演示图在动。这就是我给客户,所以这就是他们想要的东西。这只是引擎盖下闲逛之后,我很快​​就意识到,他们只是用随机数字进行更新。所以我试图做我自己。我走遍了互联网,我甚至在这里张贴了我的问题,但没有人回答。

所以,在这里就是我所做的...

起初,我试图让我的谷歌的可视化仪表板图通过AJAX来更新。我的JSON提要返回:

  [
{关键:LABEL1,值:50.25},
{关键:LABEL2,值:99.43},
{关键:LABEL3,值:4.47},
{关键:label4,值:7.06}
]

我得到了它最初呈现的静态图像,但它似乎从来没有更新。我花了一段时间,后来我想通了,我的价值观有他们周围的报价。这是问题#1:API一直在寻找数字data.It是我第一次与JSON服务。我不知道如果我需要以某种方式增加的状态:OK,或者如果我需要做一个eval()像许多其他的帖子告诉我的。好吧,我不需要任何...

我的脚本如下:

 <脚本类型=文/ JavaScript的SRC =HTTP://www.google.com/jsapi'>< / SCRIPT>
    <脚本类型=文/ JavaScript的'>
    //加载可视化API和放大器;皮肤
    的google.load('可视化','1',{软件包:['规']});
    //借鉴快速渲染快照数据初始图
    google.setOnLoadCallback(drawChart);
    //设置全局变量一旦DOM结束
    $(文件)。就绪(函数(){
      图=新google.visualization.Gauge(的document.getElementById('chart_div'));
      选项​​= {宽度:400,高度:120,
          redFrom:其中= $code_RED>中redTo:?100,
          yellowFrom:< = $code_YEL>中yellowTo:????< = $code_RED>中
          greenFrom:< = $code_GRN大于0,greenTo:????< = $code_YEL>中
          器minorTicks:5};
      //初始化图表每15秒更新阿贾克斯
      的setInterval(getStats('./getJson.sysinfo.php?dash'),15000);
     });

然后我呈现一个静态的图形搭配:

 函数drawChart(){
    VAR数据=新google.visualization.DataTable();
    data.addColumn('串','标签');
    data.addColumn('号','值');
    data.addRows(8);
    data.setValue(0,0,'label1的');
    data.setValue(0,1,&下; = number_format($ X1,2)GT;);
    data.setValue(1,0,'LABEL2');
    data.setValue(1,1,&下; = number_format($ X2,2)GT;);
    data.setValue(2,0,'LABEL3');
    data.setValue(2,1,&下; = number_format($ X3,2)GT;);
    data.setValue(3,0,'label4');
    data.setValue(3,1,&下; = number_format($ X4,3)GT;);
    chart.draw(数据,选项);
 }

这一切似乎正常工作,直到doc.ready那个讨厌的setInterval()方法在我的马虎code踢 - 15秒后。阿贾克斯源是一个PHP数组包裹着json_en code()。当脚本更新,我的整个图形消失了 - 这有点儿吸!我看到通过萤火进来的JSON。它只是不工作。请看下图:

 函数getStats(源){
  $阿贾克斯({
    网址:源,
    输入:POST,
    数据类型:JSON,
    成功:功能(数据){refreshChart(数据); },
    错误:功能(请求,状态,错误){
           警报(请求:\\ t的要求+
              +\\ n状态:\\ t+状态
              +\\ n错误:\\ t+误差);
     }
   });
 }

然后我refreshChart()是一切都只是土崩瓦解:

 函数refreshChart(serverData){
        变种chartData = [];
        对于(VAR I = 0; I< serverData.length;我++){
    // chartData.push([serverData [I] [0],$ .serverData [Ⅰ] [1] ['值']);
    // chartData.push([serverData [I] [0],$ .serverData [Ⅰ] [1] .VAL()]);
          chartData.push([serverData [I] [0],serverData [I] [1]。价值]);
        }
// note2self [347] =我试过上述一百万个不同的方式和萤火虫回来
// +搭配:在函数声明行失踪]之后元素列表...
        VAR数据=新google.visualization.DataTable();
        data.addColumn('串','标签');
        data.addColumn('号','值');
        data.addRows(chartData);
        chart.draw(数据,选项);
     }    < / SCRIPT>

我想也许我需要创建另一个DataTable对象,或者宣布它的功能外,也许我可以使用的setInterval(data.setValue(I,1,serverData的中),1500)直接更新的元素。无论哪种方式,第一步是访问JSON数据。我知道我一定是做一些愚蠢的......在我的文章的底部(此页面上,之前我再重新编辑它)我补充道:在正确的方向任何帮助,甚至是轻推将不胜AP preciated ......我每天都回来了一个星期,重新再重新编辑。我想我当时是不清楚或这是一个愚蠢的问题。 我见过愚蠢的问题得到回答,我想,也许我的是真的,真的很愚蠢吗?无 - 少,我仍然需要一个答案。虽然我不是最好的程序员 - 我是pretty良好的Google员工。我读了所有我能得到我的眼睛。没有运气。虚无缥缈,非,zylch,Niet的,没有什么...

嗯,这是我逼疯了,所以这里是我想通了:


  1. 正如我前面提到的,我在我的数值报价。这就是让我的表...炸弹,自jQuery的不给你任何错误,我是那种盲目的事实,我是馅字符数据到我的新阵,直到我叫.draw()方法和我的pretty画面消失。

  2. ,我没有想到去检查了,我使用jQuery版本的另一个问题。这是老&安培;没有把它建成JSON解析。所以,我将不得不EVAL服务器的数据,分析数据流和放大器;建立从那里的数据结构。

  3. 这两个#1安培; #2造成了数据行更新失败,​​我的领域都回来了不确定。

  4. 我也有一些变量声明超出范围 - 这来凑凑热闹 - 即增加了.Guage并顺便提及的.DataTable()类。

  5. data.setValue(I,1,serverData [I] .value的)应该已经循环了AJAX()调用的成功回调 - 这完全消除我的refreshChart()方法

  6. 我有就是如何访问JSON数据和放最后一个问题;东西到我现有阵列。这是比我想象的多一点棘手。一个更有经验的程序员很可能会只了解得......但是,我是固执。你可以看到,我试图做一个chartData.push()到现有的阵列。我打电话可能连续几晚arrayName中的[] []的每个组合。原来,我可以重新使用谷歌的.setValue()方法。正如您将在下面看到,使用成功()回调方法我能循环一次东西一日几个元素融入计,其余进去需要去其他地方,使用:

I re-wrote the whole thing from scratch. In the next few days, I will probably re-write it again, several times. Eventually this will evolve into full blown drupal & wordpress plug-ins and a how-to article. I will post it on my blog LogicWizards.NET b/c the jQuery documentation is vague and the example demo on google's site isn't very straight forward, either.

To make a long story even longer, here's what I came up with:

<!-- /** Client-Side Scripts **/ -->
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type='text/javascript'>
// load the visualization api & skin
google.load('visualization', '1', {packages:['gauge']});
// draw the initial chart from snapshot data for quick rendering
google.setOnLoadCallback(drawChart); //as soon as the API is loaded
// set global vars once DOM finishes
$(document).ready(function() {
  dash = new google.visualization.Gauge(document.getElementById('chart_div'));
  dashData = new google.visualization.DataTable();
  options = { width: 400, height: 120,
      redFrom:75, redTo:100,
      yellowFrom:50, yellowTo:75,
      greenFrom:00, greenTo:50,
      minorTicks: 5};
 });

function drawChart() {
 // method to define initial chart
    dashData.addColumn('string', 'Label');
    dashData.addColumn('number', 'Value');
    dashData.addRows(8);
    dashData.setValue(0, 0, 'CPU');
    dashData.setValue(0, 1, 54.40);
    dashData.setValue(1, 0, 'RAM');
    dashData.setValue(1, 1, 99.54);
    dashData.setValue(2, 0, 'SWAP');
    dashData.setValue(2, 1, 4.25);
    dashData.setValue(3, 0, 'NET');
    dashData.setValue(3, 1, 0.402);
    dash.draw(dashData, options);
 }

function updateJSON (source) {
 // method to update all subsequent charts
 var jsonData = null; //there's really no reason for this anymore (see below)
 $.ajax({ url:source, type:'POST', dataType:'json',
    success: function(data) { jsonData=data;
    for (var i = 0; i < data.length; i++) {
      if (i<4) {
          dashData.setValue(i, 0, jsonData[i].k);
          dashData.setValue(i, 1, jsonData[i].v);
          if (i<3) { dash.draw(dashData, options); }
        }
           $("#"+jsonData[i].k).text(jsonData[i].v);
      }
     },
    error: function (request, status, error) {
           alert("REQUEST:\t"+request
               +"\nSTATUS:\t"+status
                +"\nERROR:\t"+error);        }
   }); //end-ajax
  return jsonData; //obsolete: updates are now done through the success callback
 }

function isSet (variable) { // mimic the php function
  return (typeof variable !== "undefined" && variable.length) ? 1 : 0;
 }

function setDelay(delay){
 // method to change timer's sleep interval
    clearInterval(timer); //kill the last timer
    timer=setInterval(json,delay*1000); //delay is miliseconds
  }
</script>

You will see that the bulk of the heavy lifting is done via the updateJSON() function. and now it works pretty nicely. I figured that if I was having this many problems then somebody else might benefit from a quick edit of my original post - with me answering my own questions as I went along. I think that the process of writing my questions out for StackedOverflow helped me to tell the difference between the problems and the symptoms, and also to find the answers. Even though nobody else had an answer.

If anyone would like to see a live demo go to http://LogicWizards.NET If you need this presentation layer stuff, please feel free to steal it from the 'view source'. The guts of the application are all on the back end... Now, it took me the better part of a week to put all the pieces together. Forgive me for rambling. I will edit this when I have more time. I've just taken so much code from THIS site and the rest of the community, over the years, I feel good about giving a little bit back... just remember to vote this article up, if you use it.

I hope it helps someone who needs it.

Happy Hacking,

Joe Negron ~ NYC

解决方案

According to the project issues tracker, upgrade to 1.1 should fix the issue.

instead of

google.load('visualization', '1')

use

google.load('visualization', '1.1')

这篇关于谷歌可视化仪表动态更新使用jQuery阿贾克斯 - 从JSON供稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 02:58