JavaScript在PHP循环中不起作用

时间:2016-07-01 05:00:38

标签: javascript php html loops while-loop

似乎当我在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
}
?>

1 个答案:

答案 0 :(得分:3)

请尝试使用此

<?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
    }
  ?>