doushuo2834 2017-07-19 07:31
浏览 46

如何从PHP数组获取值到Javascript数组?

So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. First I just echo'd the array like this:

PHP:

<?php
$exampleArray = ["212", "33", "7"]
?>

and JS:

<script> var jExampleArray = <? echo json_encode($exampleArray);?>;  </script>

And then I used jExampleArray in my bar chart code. Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page. I thought about using Ajax and what not but it just didn't work for me. I got it to alert me the array, but was not able to fill a Javascript array with it.

I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. Luckily I managed to at least understand the code I wrote/copied.

Edit: [] for a JS array not {}

  • 写回答

3条回答 默认 最新

  • douzaipou3327 2017-07-19 07:35
    关注

    Some pseudo code to show how you might accomplish the stated goal

    $data=array();
    while( $rs=$db->fetch() ){
        $data[]=array(
            'field_1'   =>  $rs->field_1,
            'field_2'   =>  $rs->field_2,
            'field_3'   =>  $rs->field_3
        );
    }
    
    $json=json_encode( $data );
    
    
    <script>
        <?php
            echo "var jExampleArray={$json};";
        ?>
        /* rest of barchart code */
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决