duan01203
2014-11-07 21:11
浏览 31

如何在基于JS的Google Charts中显示PHP数组值?

The Charts documentation uses the following example:

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Toppings');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Cheese', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);

I'm building my Google Chart as follows:

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Standing');
    data.addColumn('number', 'Students');
    data.addRows([
      [<?= $users[0]->COLLEGE; ?>, <?= $users[0]->HEADCOUNT; ?>],
    ]);

But no chart is being printed. How can I use the PHP array contents to populate the chart?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drbfxb977777 2014-11-07 21:18
    已采纳

    Your code doesn't add quotes to the resulting JavaScript values (and you don't escape them). PHPs json_encode has the ability to produce valid JavaScript values from PHP strings and handle all the quotes and escaping for you so just use that:

     var data = new google.visualization.DataTable();
        data.addColumn('string', 'Standing');
        data.addColumn('number', 'Students');
        data.addRows([
          [<?= json_encode($users[0]->COLLEGE); ?>, <?= json_encode($users[0]->HEADCOUNT, JSON_NUMERIC_CHECK); ?>],
        ]);
    

    That should also prevent a whole bunch of XSS and other nasty code injection attacks and handle escaping.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题