混合javascript和php [英] mix javascript and php

查看:78
本文介绍了混合javascript和php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为: file.php

此文件中包含以下代码:

contained in this file is the following code:

<script type="text/javascript">
        //....
        var sumJS = 10;
    <?php $sumPHP = sumJS  ?>
</script>
    <?php echo "Sum = " . $sumPHP ?>

如何为$ sumPHP分配sumJS?

How can I assign sumJS for $sumPHP?

如果我想相反地做,那么我会写:

If I would like to make this conversely then I would write:

  $sumPHP = 10;
<script type="text/javascript">
    var sumJS;
    sumJS = <?php echo $sumPHP ?>;
    alert(sumJS);
</script>

但是我该如何解决我的问题呢?

But how can I re-make this for my problem?

推荐答案

$ sumPHP是服务器端值,它将在服务器上求值.然后,服务器生成页面内容,并将其发送给客户端.然后,浏览器接收页面内容并评估客户端值sumJS.

$sumPHP is a server-side value, which will be evaluated on the server. Then the server generates page content and sent it to the client. Then browsers receive the page content and evaluate client-side value sumJS.

因此您永远不能为$ sumPHP分配sumJS,因为$ sumPHP是在sumJS之前计算的.

So you can never assign sumJS for $sumPHP because $sumPHP is calculated before sumJS.

但是可以执行以下操作以显示页面:

But can do this to show the page:

<?php echo "Sum = "?><script type="text/javascript">document.write(sumJS);</script>

或更确切地说

<script type="text/javascript">document.write('Sum = ' + sumJS);</script>

这篇关于混合javascript和php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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