dongyan1974 2011-07-01 02:28
浏览 5
已采纳

将PHP变量传递给非本机JavaScript

Basically, the problem is this:

<?php $test="foobar"; ?>

If within the html document I call

<script type="text/javascript">alert("<?php echo $test; ?>")</script>

, everything is fine.

However, if I do the same thing in an external jS document included with

<script type="text/javascript" src="foo.js"></script> 

it does not work.

Is there any way to do this?

  • 写回答

3条回答 默认 最新

  • drhe80011 2011-07-01 02:34
    关注

    In the first case you actually pass the value to the PHP script, where <?php echo $test; ?> is parsed by PHP parser and replaced by the value of $test PHP variable.

    In the second case you just include '<?php echo $test; ?>' string into JS file and this is not parsed.

    My suggestion is: pass this value the way you are passing now, but properly reference it from the external JS file. For example you can invoke some function defined in JS file, passing the parameter from PHP file.

    There is also the ugly way of doing that, such as making your server treat JS files as PHP files, but I am not recommending it.

    Some example:

    If you include in your PHP file:

    <script type="text/javascript" src="foo.js"></script>
    <script type="text/javascript">myHappyFunction("<?php echo $test; ?>")</script>
    

    and in your JS file (foo.js):

    (function(){
        var myHappyFunction = function(myParameter){
            alert(myParameter);
        };
        window['myHappyFunction'] = myHappyFunction; // pass outside scope
    })();
    

    you should see $test value being alerted when the script executes (assuming I did not make a mistake writing this ;)).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度