dtoqemais553654797 2014-03-27 05:58
浏览 21
已采纳

为什么php变量无法使用javascript循环?

I expected that the number will increase on every alert, but it ended up being the same number which is 0.

Can I know why ?

I need to do this because in my real code, $wow represent the value I retrieved from server and I need to use javascript for loop to count the number element which I targeted.

How can i do this ?

Here is my Code :

<html>
<head>
<script>
<?php $wow = 0; ?>
for(var i =0; i < 4; i++){
   alert("<?php echo $wow; ?>");
    <?php $wow++; ?>
    }
</script>
<body>
</body>
</html>
  • 写回答

3条回答 默认 最新

  • duanpiao6679 2014-03-27 06:04
    关注

    PHP is executed on the server side, JavaScript on the client side.

    The way it works is like this:

    1. browser makes request
    2. server receives request
    3. server executes PHP
    4. server sends response/HTML
    5. browser receives response/HTML
    6. browser parses HTML / executes JS.

    Just have a look at the document source in the browser, there is no PHP in there because it was already executed (on the server).


    What you can do instead is inject the value of the PHP variable into the JavaScript source code and manipulate the value with JavaScript:

    var wow = <?php echo $wow; ?>
    for(var i =0; i < 4; i++){
      alert(wow);
      wow++;
    }
    

    See also

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题