2011-12-20 126 views
2

這是一個示例動態更新的圖表: http://www.highcharts.com/demo/dynamic-update如何使用AJAX獲取數據並將其存儲在JavaScript變量中?

圖表每秒更新一次與該日期作爲x值和一個隨機數作爲y值。

load: function() {    
    // set up the updating of the chart each second 
    var series = this.series[0]; 
    setInterval(function() { 
     var x = (new Date()).getTime(), // current time 
      y = Math.random(); 
     series.addPoint([x, y], true, true); 
    }, 1000); 
} 

我將如何改寫load使用AJAX,而不是在函數內部產生的值來從另一個網頁xy

+0

我需要調用服務器頁面更新x和y – Corey 2011-12-20 03:48:53

+0

的價值和服務器頁面本身的一個實例的實例 – Corey 2011-12-20 03:49:13

+0

[傳遞PHP變量返回的JavaScript變量原來頁面上的Ajax]的可能重複(http://stackoverflow.com/questions/7083998/passing-php-variables-back-to-javascript-variables-on-original-page-as-ajax) – outis 2011-12-20 10:33:42

回答

3

我想你想要什麼樣load方法,但與設置xy與AJAX調用替換線。您需要執行相當基本的continuation-passing代碼轉換,將您希望異步調用的位置之後的代​​碼轉換爲傳遞給異步調用的函數。 「Continuation」僅僅意味着「計算的其餘部分,從給定的點向前」。在代碼示例中,這是對series.addPoint的調用。這個模式是你變換:

function f(...) { 
    (1) 
    result = sync(...); 
    (2) 
} 

到:

function f(...) { 
    (1) 
    async(..., function (result) { 
      (2) 
     }); 
} 

如果(2)在原函數返回一個值,然後f通話也必須使用延續傳遞風格改寫,增加一個額外的參數來保持延續。

您應該做的另一件事是確保PHP腳本將數字對輸出爲有效的JSON,可以作爲兩個數字的數組(可以在解析後直接傳遞給series.addPoint調用),也可以作爲屬性「x」和「y」。

請注意,由於網絡通信的性質,數據可能無法及時到達,從而導致具有不規則間隔的圖形。

這裏的要點是將異步調用的功能組合成一個名爲ajaj的函數。該示例假設瀏覽器支持XMLHttpRequestJSON解析器的必要標準。

/* Asynchronous Javascript And Json */ 
function ajaj(url, succeed, fail) { 
    if (! fail) { 
     fail = function() {}; 
    } 
    var xhr = new XMLHttpRequest; 
    xhr.open('GET', url); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState==4) { 
      if (200 <= xhr.status && xhr.status < 300) { 
       succeed(JSON.parse(xhr.responseText)); 
      } else { 
       // error 
       fail(xhr.status, xhr.statusText, xhr.responseText); 
      } 
     } 
    }; 
    xhr.send(); 
    return xhr; 
} 

... 

    url: '...', 

    load: function() { 
     // ensure only one data load interval is running for this object 
     if (this.updateInterval) { 
      return; 
     } 
     // set up the updating of the chart each second 
     var series = this.series[0]; 

     this.updateInterval = setInterval(function() { 
      ajaj(this.url, 
       function(point) { // success 
        series.addPoint(point, true, true); 
       }, 
       function(status, statusText, response) { // failure 
        ... 
       } 
      ); 
     }, 1000); 
    } 

JS庫提供了自己的ajaj版本,往往更多的功能。如果您爲生產網站做任何複雜的事情,請考慮採用一個。如果你正在使用jQuery(作爲標籤建議),你可以,例如,使用jQuery.get

load: function() { 
     if (this.updateInterval) { 
      return; 
     } 
     // set up the updating of the chart each second 
     var series = this.series[0]; 

     this.updateInterval = setInterval(function() { 
      jQuery.get(this.url, 
       function(point, textStatus, jqXHR) { // success 
        series.addPoint(point, true, true); 
       }, 'json' 
      ); 
     }, 1000); 
    } 

的東西服務器端是死的簡單。 time()返回一個Unix時間戳,rand()返回一個(非常)僞隨機數(儘管對於演示足夠好),並且json_encode(),那麼你可以弄清楚。

<?php 
header('Content-type: application/json'); 

echo json_encode(
     array(
      time(), 
      rand()/getrandmax(), 
     )); 
+0

+1對於這個答案超越和超越 – 2011-12-20 15:39:55

1

我想你想setTimeout遞歸調用:

function update(series){ 
    var x = (new Date()).getTime(), // current time 
     y = Math.random(); 
    series.addPoint([x, y], true, true); 
    setTimeout(function() { update(series); }, 1000); 
} 

然後:

load: function() {    
    var series = this.series[0]; 
    update(series); 
} 

或者更好的是,嘗試這樣的事情:

function update(){ 
    var series = yourChart.series[0]; 
    var x = (new Date()).getTime(), // current time 
     y = Math.random(); 
    series.addPoint([x, y], true, true); 
    setTimeout(update, 1000); 
} 

然後:

load: update 

編輯

如果你想獲得一個隨機數作爲一個整數,這樣的事情應該這樣做(取決於你想要的號碼的範圍)

Math.floor(Math.random() * 10) 

隨機將返回範圍[0,1)中的數字,樓層將切斷任何小數點。

random docs

+0

對不起,這不正是我所期待的。我需要代碼來動態地設置每秒x和y的值。我真正需要看到的是如何發送請求並將響應以x或y形式保存爲int – Corey 2011-12-20 03:50:47

+0

@ user475160 - 請參閱我的編輯 – 2011-12-20 03:58:23

+1

@ user475160 Adam似乎有一個相當不錯的方法;請記住,只要你使用Ajax(和setTimeout),你的問題的「每一秒」部分就是最好的估計。網絡條件和setTimeout的性質將使秒到精度成爲不可能的任務。 – 2011-12-20 04:01:08

相關問題