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 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码