사용자가 데이터를 검색하기 위해 시작일과 종료일을 모두 선택하는 UI를 작업 중입니다. 이러한 데이터 중 일부는 표에 표시되며 표시된 데이터와 관련된 Google 차트를 표시하고 싶습니다.
사용자가 마지막으로 날짜를 선택하면 $.post()
다음과 같은 함수를 사용하여이 두 변수를 보냅니다 .
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
$('#button-send').click(function() {
var url_route = "{{URL::action('Controller@general_stats_post')}}";
var start_date=$('#start_date_i').val();
var end_date=$('#end_date_i').val();
var datos = {start_date: start_date, end_date:end_date,_token:_token};
보내기 버튼을 클릭하면 제대로 작동하는 $ .post () 함수를 사용합니다.
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*Here goes the google chart*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
events_types 문자열은 예를 들어 다음과 같습니다.
[['Event','Total'],['Workshop',1],['Seminar',1]]
Google의 jsfiddles 에서 완벽하게 작동합니다 .
그래서 내가 시도한 것은 다음과 같이 events_types 문자열이 존재하는 {} 안에 Google 차트의 drawChart () 함수를 넣는 것입니다.
$.post(url_route, datos, function(data,status){
if(status=='success'){
console.log('Dates sent successfully. Now the data retrieved are: '+data);
var response = jQuery.parseJSON(data);
if(response.events_types.length === 0){
console.log('events_types is empty.');
}
else{
console.log('The string for google charts got is: `'+response.events_types+'`');
/*GOOGLE CHART*/
google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(response.events_types);
var options = {
title: 'My test'
};
var chart = new google.visualization.PieChart(document.getElementById('eventos_charts'));
chart.draw(data, options);
}
/*END OF GOOGLE CHART PART*/
}
}else if(status=='error'){
console.log('Errors found');
}
});//end of .post() function
}); //end of onclick button-send
drawChart ()가 실행되었음을 알려주는 console.log 메시지를 넣었습니다. 그러나 나는 그 메시지를 결코 얻지 못합니다. 따라서 이것은 drawChart () 함수가 실행되지 않음을 의미합니다.
거의 작동-편집
이것은 작동하는 코드입니다 ...하지만 데이터 문자열을 수동으로 정의하는 경우에만 다음과 같이 말합니다.
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable([['Evento','Cantidad'],['Taller',1],['Seminario',1]]);//DEFINED MANUALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to @FABRICATOR
/**** END Google charts: Events types *********/
}
그러나 데이터를 동적으로 가져 오려고하면 :
else{
console.log('The data string is: `'+response.tipos_eventos+'`');
var the_string=response.tipos_eventos;
/***** start Google charts:*******/
//google.setOnLoadCallback(drawChart);
function drawChart() {
console.log('Inside the drawChart() function');
var data = google.visualization.arrayToDataTable(the_string);//DEFINED DYNAMICALLY
var options = {
title: 'The chart'
};
var chart = new google.visualization.PieChart(document.getElementById('events_types'));
chart.draw(data, options);
}
drawChart();//Thanks to @FABRICATOR
/**** END Google charts: Events types *********/
}
다음과 같은 오류가 발생합니다.
Uncaught Error: Not an array
작동시킬 아이디어가 있습니까? 내가 무엇을 놓치고 있습니까?
마지막으로 가장 쉬운 해결책을 찾았습니다. Laravel의 ORM (Illuminate / Database)을 사용하고 있다는 점을 감안할 때 얻은 데이터는 json 형식으로 제공됩니다.
이것은 Laravel 및 Slim 프레임 워크에서 작동합니다.
따라서 변수를 뷰에 직접 전달합니다 (Slim에서).
$app->render('home.php',[
'myArray'=>$myArray
]);
그런 다음 뷰 (이 경우 Twig 뷰. 블레이드에서 비슷해야 함) 내에서 배열을 가져 와서 Javascript 코드 내의 변수에 넣습니다.
var myArray = {{ myArray|json_encode|raw }};
그런 다음 반복해서 각 요소를 가져 와서 Google 차트 데이터 배열에 추가합니다.
$.each(myArray,function(index, value){
//console.log('My array has at position ' + index + ', this value: ' + value.r1);
data.addRow([value.col1,value.col2,value.col3,value.col4]);
});
그리고 그것은 지금 작동합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다