duandiaoqian5795 2014-10-03 12:37
浏览 61
已采纳

我可以在PHP内部的JavaScript中编写PHP吗? [重复]

This question already has an answer here:

Inside a PHP script I have this:

echo <<<EOD

<script type="text/javascript">
document.getElementById('my_element_id').innerHTML='Do stuff';
</script>

EOD;

Can I add PHP inside the JavaScript? Replace the "Do stuff" part with PHP code? If yes, how do I do it?

</div>
  • 写回答

3条回答 默认 最新

  • douxin0251 2014-10-03 12:44
    关注

    First of all, it should be noted that this has nothing to do with javascript. You could have any form of text. Your actual question is how to use a variable inside of a heredoc.

    Heredoc is defined as the following:

    Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.

    Meaning that since this works:

    $name = 'Foo';
    
    echo "My name is $name"; // Using double quotes so variables get expanded
    

    Then this also works:

    $name = 'Foo';
    
    echo <<<EOD
        My name is <strong>$name</strong>
    EOD;  // Using heredoc so variables get expanded
    

    Essentially meaning that yes, as long as you put your 'Do stuff' content into a variable first. Note that if you use more advanced variables/arrays, it's a good idea to do a $array = json_encode($array) before pasting it into JS code (imagine if $name was The Boss's Wife - then the apostrophe would ruin your JS if you don't encode it).

    DEMO

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

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决