将php插入javascript片段

时间:2014-08-13 20:43:44

标签: javascript php

从我在搜索功能中看到的内容,javascript绝对需要。当我在disqus_identifier和disqus_title的示例变量中进行子操作时,此脚本工作正常,但是当我尝试使用已存储在页面中的php变量时,它会中断!

<div id="disqus_thread"></div>
<script>
    var disqus_shortname = 'sample';

    var disqus_config = function () {
      this.page.remote_auth_s3 = '*********';
      this.page.api_key = '********';
}
</script>

<script type="text/javascript">
        /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
        var disqus_identifier = "/posts/"<?php var_dump($postid); ?>;
       var disqus_title = <?php var_dump($title); ?>;

       /* * * DON'T EDIT BELOW THIS LINE * * */
       (function() {
         var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
       })();
</script>

<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

1 个答案:

答案 0 :(得分:3)

var_dump()不是你想要的,因为它“转储有关变量的信息”,而不仅仅是回显内容。 (Docs)你想获取$ postid并渲染变量中包含的文字字符串。

使用

<?php echo $postid ?>

<?=$postid?>

代替。

如果你想要字符串文字而不是int表示,你还需要用引号括起来,所以

var post_id = "<?=$post_id?>";

将起作用或

var post_id = "This <?=$post_id?> is great";