如何在javascript中遍历php中的数据



我想问如何在javascript中重复一个区域?数据是动态的,我想找到所有项目通过php do...while循环:

<script type="text/javascript">
    window.onload = function () {
    <?php do{ ?>
        var chart<?php echo $row_RecAllAnswers['q_id']; ?> = new CanvasJS.Chart("<?php echo $row_RecAllAnswers['q_id']; ?>", {
            theme: "theme2",//theme1
            title:{
                text: "No. " + "<?php echo $row_RecAllAnswers['q_id']; ?>"              
            },
            animationEnabled: true,   // change to true
            data: [              
            {
                // Change type to "bar", "splineArea", "area", "spline", "pie",etc.
                type: "column",
                dataPoints: [
                    { label: "A" ,  y: <?php echo $row_RecAllAnswers['A']; ?>  },
                    { label: "B", y: <?php echo $row_RecAllAnswers['B']; ?>  },
                    { label: "C", y: <?php echo $row_RecAllAnswers['C']; ?>  },
                    { label: "D",  y: <?php echo $row_RecAllAnswers['D']; ?>  }
                ]
            }
            ]
        });
        chart<?php echo $row_RecAllAnswers['q_id']; ?>.render();
        chart<?php echo $row_RecAllAnswers['q_id']; ?> = {};
        window.alert(<?php echo $row_RecAllAnswers['q_id']; ?>);
        <?php } while ($row_RecAllAnswers = mysql_fetch_assoc($RecAllAnswers));  ?> 
    }
</script>
    使用json_encode将mysql查询结果转换为JSON。将JSON写入你的HTML。
  1. 在Javascript中使用foreach来迭代JSON数组。

json将PHP数组编码为javascript变量,然后循环遍历该变量。在twig中,我是这样做的:

var objectName = {{ phpVariable|json_encode|raw }};

所以我认为这应该可以在PHP中找到(没有测试它):

var objectName = <?php echo json_encode($phpVariable); ?>;

然后javascript变量'objectName'将包含您的数据,现在您可以使用常规javascript来循环遍历数据。您也可以使用下划线,因为它更容易。

_.each(objectName, function(item, key){
//do stuff here
});

相关内容

  • 没有找到相关文章

最新更新