我想你想要什麼樣load
方法,但與設置x
和y
與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
的函數。該示例假設瀏覽器支持XMLHttpRequest和JSON解析器的必要標準。
/* 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(),
));
我需要調用服務器頁面更新x和y – Corey 2011-12-20 03:48:53
的價值和服務器頁面本身的一個實例的實例 – Corey 2011-12-20 03:49:13
[傳遞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