为什么 flot 不适用于 (x,y) 值数组? Javascript 对象还是数组?

Why doesn't flot work with a array of (x,y) values? Javascript object versus arrays?

我正在使用一些 php-脚本创建一个浮点图。 php 生成数据并使用 json_encode 将此数据传递给一些 javascript-flot 代码,我在其中使用 jQuery.parseJson.

进行解析

我使用的是 data 数组,其中填充了 (x,y) 值。绘制这似乎不起作用。如果我将数组封装在对象 flot 中,则可以毫无问题地绘制它。为什么第一种方法不起作用?我在下面添加了一个 jsFiddle。

var data = '[["201518","1"],["201519","3"],["201520","6"]]',
    data2 = '{"data":[["201518","1"],["201519","3"],["201520","6"]]}';

var set = jQuery.parseJSON(data),
    set2 = jQuery.parseJSON(data2);

var placeholder = $('#placeholder');
$.plot(placeholder, [set2.data]);
//$.plot(placeholder, set); <= not working? Why?

jsfiddle

您需要传递一个数组:

$.plot(placeholder, [set])
// instead of `$.plot(placeholder, set)`

两个问题。首先,当作为数组传递时,您需要数字而不是字符串(请参阅 here 它说的

Note that to simplify the internal logic in Flot both the x and y values must be numbers (even if specifying time series, see below for how to do this). This is a common problem because you might retrieve data from the database and serialize them directly to JSON without noticing the wrong type. If you're getting mysterious errors, double check that you're inputting numbers and not strings.

其次(正如另一个答案中指出的那样),您需要 [array] around set。以下作品:

$(document).ready(function () {
    var data = '[[201518,1], [201519,3], [201520,6]]',
        data2 = '{"data":[["201518","1"],["201519","3"],["201520","6"]]}';

    var set = jQuery.parseJSON(data),
        set2 = jQuery.parseJSON(data2);

    var placeholder = $('#placeholder');
    //$.plot(placeholder, [set2.data]);
    $.plot(placeholder, [set]);
});