似乎当我在php中回显结果时,它将循环遍历数据库并在下面的“ echo”中显示它,但是如果我尝试使用javascript显示它,它甚至不会循环。 javascript中有什么问题?

<?php
while($row = $result->fetch()){
    $id = $row['id'];

    echo $id; //loops through and displays the all the id's in order in the database
    ?>

    //this only displays the first id and doesn't loop even though it is in the php while loop
    <script>
        document.getElementById("test").innerHTML = "<?= $id ?>";
    </script>
    <span id="test"></span>

    <?php
}
?>

最佳答案

请尝试这个

<?php

while($row = $result->fetch()){
$id = $row['id'];

echo $id; //loops through and displays the all the id's in order in the database
?>

//this only displays the first id and doesn't loop even though it is in the php while loop

 <!-- change in id name -->
<span id="test_<?=$id?>"></span>

<script type="text/javascript">
   //change here
    document.getElementById("test_<?=$id?>").innerHTML = "<?= $id ?>";
</script>
<?php
    }
  ?>

10-01 00:59
查看更多