dsa45664 2019-07-22 23:38
浏览 95
已采纳

js变量在php里面循环[重复]

This question already has an answer here:

I am familiar with php but still learning Js. Some people helped me on completing a ajax form to send data to mysql. But now I am stuck on below:

I used while loop as I want to print every thing which matches query

while($row = mysqli_fetch_assoc($result))
{
     comment_id = $row['comment_id'];
     echo "<script>";
     echo "var count = ".json_encode($comment_id);
      echo "</script>";
    }

But what I get a last value on while loop is assigned to js variable count as php is server sided and js is client sided. Then I tried adding array (as it can hold many values)

    while($row = mysqli_fetch_assoc($result)) 
{
    $comment_id = $row['comment_id'];
     echo "<script>";
                                    echo "var count = [];";
                                    echo.     "count.push($com);";
                                    echo "</script>"; 
}

But again i am getting last value in while loop. Is there any way I can assign whole data inside a php while loop to js variable.

Thanks :)

</div>
  • 写回答

1条回答 默认 最新

  • dongxi7609 2019-07-23 01:36
    关注

    I just got an idea and I think it is now resolved. I did is taken a php array inside while loop and assigned it to js array.

        $count = [];
        while($row = mysqli_fetch_assoc)
        $comment_id = $row['comment_id'];
         array_push($count,$comment_id);
        echo "<script>";
        echo "var count =".json_encode($count);
        echo "</script>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?