在Javascript中使用Javascript中的PHP变量 [英] Using PHP Variables in Javascript with JSON

查看:78
本文介绍了在Javascript中使用Javascript中的PHP变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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变量?

I want to use a php array inside javascript for loop but i don't want to reopen php tags inside <script></script> tags. How can i use php variables in javascript?

推荐答案

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

如果你真的不想在JS里面打开php标签,你就必须发行对服务器的ajax请求并异步获取数据。然后你的代码看起来像这样(使用jQuery来表示简短性):

If you really don't want to open php tags inside your JS, you'll have to issue an ajax request to the server and grab the data asynchronously. Then your code would look like this (using jQuery for shortness):

$.getJSON('/url/that/responds/with/json', function(heros) {
   for(i=0; i<3; i++)
   {  
      if(heros[i]=='Spiderman')
      {
        alert('Hey! I am Spiderman.');
      }
   } 
});

这篇关于在Javascript中使用Javascript中的PHP变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆