繁体   English   中英

遇到在JavaScript代码中插入php变量的麻烦

[英]Facing trouble to insert php variable in javascript code

我正在尝试在JavaScript代码中插入php变量,但无法获得结果。 代码是:

<?php $twitterusername = get_option_tree( 'twitter_name', '', 'true' );?>

<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=$twitterusername&settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>

实际上,我的文本编辑器未在脚本内将$ twitterusename标记为有效的php代码。 请帮帮我。

这不是有效的php代码,您需要使用<?php echo $twitterusername; ?>进行标记<?php echo $twitterusername; ?> <?php echo $twitterusername; ?>

您的最终代码如下所示:

<?php $twitterusername = get_option_tree( 'twitter_name', '', 'true' );?>

<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?php echo $twitterusername; ?>&settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>

尝试这个:

<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?php echo $twitterusername;?>settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>

由于它是一个PHP变量,因此您需要使用PHP(而不是JavaScript)将其回显。

所以你需要更换

$twitterusername

<?php echo $twitterusername; ?>

即使它位于<script>标记内,只要在PHP标记中,它将回显任何$twitterusername

如果您的服务器支持简码,则可以使用

<?=$twitterusername;?>

使其略短。

<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?=$twitterusername;?>settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>

您需要使用php标记( <? ?> )插入变量。

<script type="text/javascript">document.write(unescape("%3Cscript src='http://twitterforweb.com/twitterbox.js?username=<?=$twitterusername?>&settings=0,1,2,248,279,ffffff,0,c4c4c4,101010,1,1,336699' type='text/javascript'%3E%3C/script%3E"));</script>

这是因为您在PHP标记之外使用了PHP变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM