如何在JavaScript代码中访问PHP变量? [英] How to access PHP variable in JavaScript code?

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

问题描述

我有一个PHP代码变量,我想在我的JavaScript函数中访问它。以下是我的代码。

I have a variable in PHP code which I want to access in my JavaScript function. Below is my code.

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>

在JavaScript代码中访问php代码中声明的变量有哪些方法?

What are the ways to access I variable declared in php code in the JavaScript code?

推荐答案

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

You can access a PHP variable inside javascript by echoing it within quotes if the value is a string and just need to echo if it is an integer, like;

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

这篇关于如何在JavaScript代码中访问PHP变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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