0
<?php
   $heros=array("Spiderman","Batman","Superman");
?>

<script type="text/javascript">
   var heros = <?php echo $heros;?> // I don't want to do this.
   for(i=0; i<3; i++)
   {  
      if(heros[i]=='Spiderman')
      {
        alert('Hey! I am Spiderman.');
      }
   }
</script>

我想在 javascript for 循环中使用 php 数组,但我不想在标签内重新打开 php<script></script>标签。如何在 javascript 中使用 php 变量?

4

3 回答 3

5
var heros = <?php echo json_encode($heros);?> // You have to do this.

如果您真的不想在 JS 中打开 php 标签,则必须向服务器发出 ajax 请求并异步获取数据。然后您的代码将如下所示(使用 jQuery 表示简短):

$.getJSON('/url/that/responds/with/json', function(heros) {
   for(i=0; i<3; i++)
   {  
      if(heros[i]=='Spiderman')
      {
        alert('Hey! I am Spiderman.');
      }
   } 
});
于 2013-08-15T20:24:37.897 回答
0

就直接方式而言,bfavaretto 是正确的。

如果您经常遇到此类问题,您可以考虑更通用的解决方案;我们的应用程序有一个“上下文”变量,其中包含在 PHP 中多次操作的字符串索引值。然后,作为我们标头代码的一部分,它的内容被初始化为一个 Javascript 变量。显然,我们只将它用于我们打算向客户公开的东西。像这样的东西:

<?php
include('header1.php');
$context['heroes'] = array('Spiderman', 'Batman');

...do some extra processing with this context variable...
include('header2.php');
?>

<script>
  var heroes = myApp.context.heroes;
</script>
于 2013-08-15T20:29:59.347 回答
-1

错误的解决方案:

您可以在php中回显所有javascript代码,然后使用json编码,这是您不需要在javascript标签中重新打开php标签的唯一方法。

解决方案:

只需使用已经给出的答案:

var heros = <?php echo json_encode($heros);?> // You have to do this.
于 2013-08-15T20:29:47.423 回答