JavaScript — GoogleChart JSON

Попытка создать Google GANTT Chart с использованием данных JSON через PHP и AJAX на локальном хосте. Я получаю следующую ошибку. Я не могу понять ошибку и как она загружается.

Uncaught TypeError: Cannot read property '3' of undefined
at gvjs_Tba (jsapi_compiled_default_module.js:132)
at new gvjs_R (jsapi_compiled_default_module.js:131)
at Object.<anonymous> (ganttchart.html:23)
at c (jquery.min.js:4)
at Object.fireWith [as resolveWith] (jquery.min.js:4)
at k (jquery.min.js:6)
at XMLHttpRequest.r (jquery.min.js:6)
gvjs_Tba @ jsapi_compiled_default_module.js:132
gvjs_R @ jsapi_compiled_default_module.js:131
(anonymous) @ ganttchart.html:23
c @ jquery.min.js:4
fireWith @ jquery.min.js:4
k @ jquery.min.js:6
r @ jquery.min.js:6
XMLHttpRequest.send (async)
send @ jquery.min.js:6
ajax @ jquery.min.js:6
drawChart @ ganttchart.html:18
Promise.then (async)
google.G.K.U.hl @ loader.js:231
(anonymous) @ ganttchart.html:11

Мой HTML DOC, где я делаю AJAX ссылку на страницу PHP. Я изменил вызов AJAX из предыдущей версии, чтобы включить выполненный

  <html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

google.charts.load('current', {'packages':['gantt']});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {
$.ajax({
url: "getGanttData.php", // make this url point to the data file
dataType: "json"}).done(function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

var options = {
//explorer: {axis: 'horizontal'}
height: 275,
gantt: {
defaultStartDateMillis: new Date(2019, 1, 1)
}
};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</head>

<body>

<div id="intro">
<h1>Supervisor's Dashbaord</h1>
</div>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>

PHP Script — это читает пример строки подробностей Ганта и извлекает данные: getGanttData.php

<?php

$string = file_get_contents("sampleGanttData.json");
echo $string;

?>

Мои данные JSON: sampleGanttData.json

    {
"cols": [{"id": "ID", "label": "Task ID", "type": "string"},
{"id": "Name", "label": "Task Name", "type": "string"},
{"id": "Resource", "label": "Resource", "type": "string"},
{"id": "Start", "label": "Start Date", "type": "date"},
{"id": "End", "label": "End Date", "type": "date"},
{"id": "Duration", "label": "Duration", "type": "number"},
{"id": "Percent", "label": "Percentage complete", "type": "number"},
{"id": "Dependencies", "label": "Dependencies", "type": "string"}
],
"rows": [
{"c":[{"v": "T101"},
{"v": "WO:1 - create Design"},
{"v": "Engineer"},
{"v":"null"},
{"v":"null"},
{"v": 2.0},
{"v": 2.0},
{"v":"null"}
]},

[{"c":[{"v": "T102"},
{"v": "WO:1 - Gain Design Approval"},
{"v": "Engineer"},
{"v":"null"},
{"v":"null"},
{"v": 3.0},
{"v": 0.0},
{"v":"T101"}
]}
]
]
}

1

Решение

да, вам нужно будет удалить async: false снять предупреждение об устаревании

тем не менее, это приведет к выполнению остальной части кода диаграммы до того, как данные будут возвращены,
что приведет к другой ошибке

так как success функция также устарела,
переместить остальную часть кода в done обещаю исправить проблему,
следующее…

// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['gantt']});

// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);

function toMilliseconds(hour) {
return hour * 60 * 1000 *60;
}

function drawChart() {
$.ajax({
url: "getGanttData.php", // make this url point to the data file
dataType: "json"}).done(function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);

var options = {
//explorer: {axis: 'horizontal'}
height: 275,
gantt: {
defaultStartDateMillis: new Date(2019, 1, 1)
}
};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
});
}

ОБНОВИТЬ

данные JSON искажены. во втором ряду есть дополнительная открывающая и закрывающая скобка массива, см. комментарии.

{
"cols": [{"id": "ID", "label": "Task ID", "type": "string"},
{"id": "Name", "label": "Task Name", "type": "string"},
{"id": "Resource", "label": "Resource", "type": "string"},
{"id": "Start", "label": "Start Date", "type": "date"},
{"id": "End", "label": "End Date", "type": "date"},
{"id": "Duration", "label": "Duration", "type": "number"},
{"id": "Percent", "label": "Percentage complete", "type": "number"},
{"id": "Dependencies", "label": "Dependencies", "type": "string"}
],
"rows": [
{"c":[{"v": "T101"},
{"v": "WO:1 - create Design"},
{"v": "Engineer"},
{"v":"null"},
{"v":"null"},
{"v": 2.0},
{"v": 2.0},
{"v":"null"}
]},

// the following opening brace ([) should be removed
[{"c":[{"v": "T102"},
{"v": "WO:1 - Gain Design Approval"},
{"v": "Engineer"},
{"v":"null"},
{"v":"null"},
{"v": 3.0},
{"v": 0.0},
{"v":"T101"}
]}
]  // <-- one of these closing braces should be removed
]  // <-- one of these closing braces should be removed
}

Кроме того, если вы собираетесь использовать null значение, оно не должно быть в кавычках.

{"v":"null"}  // <-- bad
{"v":null}    // <-- good

однако, по крайней мере, одна строка должна иметь дату начала и окончания,
в предоставленном образце данных обе строки имеют нулевые даты.

очистка JSON должна позволить рисовать диаграмму,
см. следующий рабочий фрагмент …

google.charts.load('current', {
packages: ['gantt']
}).then(function () {
var data = new google.visualization.DataTable({
"cols": [
{"id": "ID", "label": "Task ID", "type": "string"},
{"id": "Name", "label": "Task Name", "type": "string"},
{"id": "Resource", "label": "Resource", "type": "string"},
{"id": "Start", "label": "Start Date", "type": "date"},
{"id": "End", "label": "End Date", "type": "date"},
{"id": "Duration", "label": "Duration", "type": "number"},
{"id": "Percent", "label": "Percentage complete", "type": "number"},
{"id": "Dependencies", "label": "Dependencies", "type": "string"}
],
"rows": [
{"c":[
{"v": "T101"},
{"v": "WO:1 - create Design"},
{"v": "Engineer"},
{"v": null},
{"v": null},
{"v": 2.0},
{"v": 2.0},
{"v": null}
]},
{"c":[
{"v": "T102"},
{"v": "WO:1 - Gain Design Approval"},
{"v": "Engineer"},
{"v": "Date(2019, 1)"},
{"v": "Date(2019, 2)"},
{"v": 3.0},
{"v": 0.0},
{"v": "T101"}
]}
]
});

var options = {
height: 275,
gantt: {
defaultStartDateMillis: new Date(2019, 1, 1)
}
};

var chart = new google.visualization.Gantt(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector