调用Javascript函数没有任何按钮在PHP中触发它

calling Javascript function without any button to trigger it in PHP

本文关键字:PHP 按钮 函数 Javascript 任何 调用      更新时间:2023-09-26

好吧,在我进入编码的另一个阶段之前,只是为了确保我不会在错误的树上吠叫,我可以问一下是否可以在 php 中调用一个 javascript 函数,而无需任何按钮单击操作来触发它。 我也不考虑 onload() 或 onready(),因为我将在 PHP 中的 foreach 循环中调用 JavaScript 函数。

<script type="text/javascript">
   function callMe(){
      alert('im called!');
   }
</script>
<body>
  <?php
    .....
    foreach($somevar as $var){
     // assuming it will loop 5 times
    callMe();  // well this is the part where im going to call the javascript function
   }
  ?>
</body>

提前谢谢你。

编辑部分**

以下是我计划使用的实际代码:

function AddCoordinate( lat, long )                                                                                                                                   
{
  var path = LinePath.getPath(); 
  path.push( new google.maps.LatLng( lat, long ) );
}

<?php    
    foreach($arrayOfPlotPoints as $key => $value){ 
        $longitude = round($value['longitude'],5);
        $latitude = round($value['latitude'],5);
        $snrLevel = $value['snr_level'];
        echo '<script         
            type="text/javascript">AddCoordinate('.$latitude.','.$longitude.')</script>
?>

其实这是正确的答案。它已经奏效了..所以我也会提供一个答案

只需输出以下内容:

echo '<script type="text/javascript">callMe()</script>';

感谢多纳塔斯..现在这就是我所拥有的:

function AddCoordinate( lat, long )                                                                                                                                   
{
  var path = LinePath.getPath(); 
  path.push( new google.maps.LatLng( lat, long ) );
}

<?php    
    foreach($arrayOfPlotPoints as $key => $value){ 
        $longitude = round($value['longitude'],5);
        $latitude = round($value['latitude'],5);
        $snrLevel = $value['snr_level'];
        echo '<script         
            type="text/javascript">AddCoordinate('.$latitude.','.$longitude.')</script>
?>

它适用于:)