简体   繁体   English

如何在JavaScript代码中访问PHP变量?

[英]How to access PHP variable in JavaScript code?

I have a variable in PHP code which I want to access in my JavaScript function. 我有一个PHP代码变量,我想在我的JavaScript函数中访问它。 Below is my code. 以下是我的代码。

myfile.php myfile.php

<?php
  $i = 0;
?>
<html>
  <head>
    <script type="text/javascript">
      function SetText() {
        //I want to access value of i here
        //alert(i);
      }
    </script>
  </head>
  <body>
    <button type="button" id="mybutton" onclick="SetText()">Click ME</button>
  </body>
</html>

What are the ways to access I variable declared in php code in the JavaScript code? 在JavaScript代码中访问php代码中声明的变量有哪些方法?

如果值是一个字符串,你可以通过在引号中回显它来访问javascript中的PHP变量,只要它是一个整数就需要回显,比如;

var i=<?php echo $i; ?>;  

SetTextUse this SetText使用这个

<button type="button" id="mybutton" onclick="SetText(<?php echo $i; ?>)">Click ME</button>    

And in Javascript use this 并在Javascript中使用此

function SetText(id)
{
alert(id);
}

reference ! 参考

i am using this code for access it's working you can try it 我正在使用此代码访问它的工作,你可以尝试

var abc = <? php echo $a; ?>

alert(abc);

Try this 尝试这个

<script>
      window.myVar = <?php echo $i; ?>;
</script>

or put all your variables (which you wanna paas to ui/js) into some array 或者把你所有的变量(你想把它们放到ui / js中)放到一些数组中

and define this function 并定义此功能

function sendToJS($array){
     for (var $i in $array){
       echo  'window.'.$i.'="'.$array.'";' 
     }
}

then in your html/php file 然后在你的html / php文件中

<script><?php 
    sendToJS($myVars);
?></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM