简体   繁体   English

将数组数据从PHP传递到Javascript

[英]passing array data from PHP to Javascript

I am fetching an array from a MySQL result into a array variable. 我正在从MySQL结果中获取数组到数组变量中。 I can successfully use a simple php echo line in the javascript beneath to grab the first $row element, but I want to use json_encode to get the whole array at once. 我可以在下面的javascript中成功使用一条简单的php echo行来获取第一个$ row元素,但是我想使用json_encode一次获取整个数组。

When I do this and try to set a javascript var to the first array element something goes wrong and even the single var method stops working. 当我这样做并尝试将javascript var设置为第一个数组元素时,出现了问题,甚至单个var方法也停止了工作。

<?php
.
.
.
    while($row = $result->fetch_array(MYSQLI_NUM)) {
        $row1 = $row[0];
    }       
?>

<script type="text/javascript">  
    var RowArray = <?php echo json_encode($row); ?>;
    var RA1 = RowArray[0];
    window.alert(RA1);

    var Row1 = '<?php echo $row1; ?>';      
    window.alert(Row1);     
</script>  

Make an array containing all the records: 创建一个包含所有记录的数组:

$rows = [];
while ($row = $result->fetch_array(MYSQLI_NUM))
{
   // do custom modifications to $row if neededed
   $rows[] = $row; // push to array
}

Or just: 要不就:

$rows = $result->fetch_all(MYSQLI_NUM);

And then use json_encode() with $rows . 然后将json_encode()$rows

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM