Error: Not an array in Google charts

我的梦境 提交于 2019-12-24 01:33:50

问题


I have manage to output the results from the database by outputting the following string:

[['Grupo de edad','Mujeres','Hombres'],['Menos de 40',2,0],['De 40 a 49',7,3],['De 50 a 59',8,5],['De 60 a 69',20,25],['De 70 y más',6,10]]

If i paste exactly this text into the following:

var data = google.visualization.arrayToDataTable([['Grupo de edad','Mujeres','Hombres'],['Menos de 40',2,0],['De 40 a 49',7,3],['De 50 a 59',8,5],['De 60 a 69',20,25],['De 70 y más',6,10]]);

I can visualize correctly the chart.

However, if i get the data by using jQuery .get() function and then i pass the data to google visualization function like the following:

google.load("visualization", "1.1", {packages:["corechart","bar"]});
google.setOnLoadCallback(drawVisualization);

function drawVisualization() {
    $.get("{{URL::action('ChartController@investigadoresEdadSexo')}}", function(datos, status){
        var data = google.visualization.arrayToDataTable(datos);
        var options = {
            //many options ...
        };

        var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    });//End of jQuery .get
}

I get the

Not an Array error

I know that i am passing a string, but why doesn't it work if i have tested that string by typing (copying and pasting) google.visualization.arrayToDataTable() function? Or how do i make that function interpret that string as an array?

How do i fix this?


回答1:


Try to convert datos to an array using JSON.parse:

var data = google.visualization.arrayToDataTable(JSON.parse(datos));

UPDATE

Before parsing datos quotes ' should be transformed to ":

datos = datos.replace(/'/g, '"');
var data = google.visualization.arrayToDataTable(JSON.parse(datos));



回答2:


When you're pasting your first text right into the function you are not pasting text, you're creating an Array element which is used by the arrayToDataTable function.

As @phts pointed out, you must parse your string to create an Array element from it. Set the dataType parameter to "json" and it'll get a JSON object as result.




回答3:


Thank you so so much phts!!! I was getting really weird lines before the code also when generating the arraylist using jsp...

If anybody's having issues with their jsp code this is how I did it.

Connection con = (Connection) session.getAttribute("conexao");
Locale.setDefault(Locale.GERMAN);
if (con == null) {
    response.sendRedirect("fimsessao.html");
    return;
}
request.setCharacterEncoding("UTF-8");
Statement st;
ResultSet rs;
String cod = String.valueOf(session.getAttribute("cod"));

//Variáveis de Insert e Update
SimpleDateFormat dt = new SimpleDateFormat("yyyy/MM");
String dates = null;
double peso = 0;
ArrayList relPeso = new ArrayList();
relPeso.add("['Datas'");
relPeso.add("'Peso']");
try {

    String query = "SELECT `data`, `peso` FROM asaacademia.tblavaliacaofis WHERE idUsuario = '" + cod + "';";
    PreparedStatement pstm = con.prepareStatement(query);
    rs = pstm.executeQuery();
    while (rs.next()) {
        dates = dt.format(rs.getTimestamp(1));
        peso = rs.getDouble(2);
        relPeso.add("['" + dates + "'");
        relPeso.add(String.valueOf(peso) + "]");
    }

    out.print(relPeso);
    System.out.print(relPeso);


} catch (Exception e) {
    e.printStackTrace();
}

Also used this instead jQuery.parseJSON(queryObject) as per:

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/

And here is my HTML code:

<div class="well">
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        google.setOnLoadCallback(drawChart);
        //Puxar os dados do relatório de peso.
        var queryObject = "";
        $.ajax({
            url: 'peso.jsp',
            success: function (data) {
                queryObject = data;
                //alert(data);
            },
            error: function (xhr, type) {
                alert('server error occoured')
            }
        });

        function drawChart() {
            // Create and populate the data table. [['Datas', 'Peso'], ['2016/05', 95.0], ['2016/05', 93.0], ['2016/05', 92.0]]
            //var data = google.visualization.arrayToDataTable([['Datas', 'Peso'], ['2016/05', 95.0], ['2016/05', 93.0], ['2016/05', 92.0]]);
            //jQuery.parseJSON()
            queryObject = queryObject.trim();
            queryObject = queryObject.replace(/'/g, '"');
            queryObject = jQuery.parseJSON(queryObject);
            var data = google.visualization.arrayToDataTable(queryObject);
            var options = {
                vAxis: { title: 'Peso em KG' }
            };
            // Create and draw the visualization.
            new google.visualization.LineChart(
            document.getElementById('divPeso')).draw(data, options);
        }
    </script>
    <h3>Peso</h3>
    <div id="divPeso"></div>
</div>


来源:https://stackoverflow.com/questions/29500787/error-not-an-array-in-google-charts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!