如何使用AJAX来获取数据并将其存储在JavaScript变量?如何使用、变量、数据、并将其

2023-09-10 20:04:20 作者:红尘不醉我独醉

这是一个简单的动态更新图: http://www.highcharts.com/demo/dynamic-update

This is a sample dynamically updated chart: http://www.highcharts.com/demo/dynamic-update

的图表每秒更新一次用的时间作为x值和一个随机数作为y值。

The chart is updated every second with the the date as the x value and a random number as the y value.

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);
}

我将如何改写负荷来获取 X 在函数中使用AJAX,而不是生成的数值另一个网页?

How would I rewrite load to fetch x and y from another webpage using AJAX, rather than generating the values within the function?

推荐答案

我想你想要什么样负荷方法,但与集线 X 替换为AJAX调用。你需要执行一个相当基本的延续传递 code转型,转向code你想要的异步调用成传递给此异步调用的函数后点。 延续只是手段计算的其余部分,从一个给定的点向前。在code样品,这是调用 series.addPoint 。该模式因为这是你改变:

I take it what you want is the sample load method but with the lines that set x and y replaced with an AJAX call. You'll need to perform a fairly basic continuation-passing code transformation, turning the code after the point you want the asynchronous call into a function that's passed to the asynchronous call. "Continuation" simply means "the rest of the calculation, from a given point forward". In the code sample, that's the call to series.addPoint. The pattern for this is you transform:

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

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

如果(2)在原函数返回一个值,则f 调用也必须使用延续传送风格改写,添加一个额外的参数来保存延续

If (2) returned a value in the original function, then the call to f must also be rewritten using continuation passing style, adding an extra parameter to hold the continuation.

你应该做的另一件事是确保PHP脚本输出的数字对作为有效的JSON,无论是作为两个数字(可以直接传递到 series.addPoint 解析后的呼叫),或作为一个对象的属性X和Y。

The other thing you should do is make sure the PHP script outputs the numeric pair as valid JSON, either as an array of two numbers (which can be passed directly to the series.addPoint call after parsing), or as an object with properties "x" and "y".

请注意的是,由于网络通​​信的性质,所述数据可能未到达及时,导致与不规则的间隔的曲线图。

Note that, due to the nature of network communication, the data may not arrive in a timely manner, resulting in a graph with irregular intervals.

这里的要点,结束了螺母和螺栓的异步调用到一个名为函数 AJAJ 。该样例假定浏览器支持的必要标准的 XMLHtt prequest 并在 JSON解析器

Here's the gist, wrapping up the nuts-and-bolts of the asynchronous call into a function named ajaj. The sample assumes the browser supports the necessary standards for XMLHttpRequest and the JSON parser.

/* 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

JS libraries provide their own version of ajaj, often with more features. If you're doing anything of any complexity for a production site, look into adopting one. If you're using jQuery (as the tag suggests), you can, for example, use 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);
    }

东西服务器端是死的简单。 时间() 返回Unix时间戳,的 兰特() 返回(不是很)伪随机数(虽然不够好演示),和 json_en code() ,好了,你可以明白这一点。

The server side of things is dead simple. time() returns a Unix timestamp, rand() returns a (not very) pseudorandom number (though good enough for a demo), and json_encode(), well, you can figure that out.

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

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