如何在JavaScript中嵌入PHP代码? [英] How do I embed PHP code in JavaScript?

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

问题描述

我们如何在JavaScript中使用PHP代码?

How can we use PHP code in JavaScript?

function jst()
{
    var i = 0;
    i = <?php echo 35; ?>
    alert(i);
}

请建议更好的方式。

推荐答案

如果您的整个JavaScript代码都由PHP处理,那么您可以这样做。如果您有单独的.js文件,并且您不希望PHP处理它们(例如,出于缓存原因),那么您只需在JavaScript中传递变量即可。例如,在index.php(或指定布局的任何地方),你可以这样做:

If your whole JavaScript code gets processed by PHP, then you can do it just like that. If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript. For example, in your index.php (or wherever you specify your layout), you'd do something like this:

<script type="text/javascript">
    var my_var = <?php echo json_encode($my_var); ?>;
</script>

然后您可以在JavaScript中使用 my_var 文件。此方法还允许您传递除简单整数值之外的其他值,因为json_encode()也正确处理数组,字符串等,将它们序列化为JavaScript可以使用的格式。

You could then use my_var in your JavaScript files. This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serializing them into a format that JavaScript can use.

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

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