简体   繁体   English

PHP带有变量的Echo JavaScript

[英]Php echo javascript with variables

have a question about a php echoing script that has a link to a javascript with some variables. 有一个关于php echo脚本的问题,该脚本具有指向带有某些变量的javascript的链接。 I need to know the format for the echo so it will work properly. 我需要知道回声的格式,以便它可以正常工作。 Could anyone shed any light on this? 谁能对此有所启示? My code is posted below 我的代码发布在下面

echo "<a href='javascript: toggle('variable1', 'variable2')'><label1 for='nameEditor'>Manage</label1></a>";

Now when you hover over the link it just shows javascript:toggle( Now I have tried multiple things and I still cant get it to work. Anyone have any suggestions? 现在,当您将鼠标悬停在链接上时,它只会显示javascript:toggle(现在,我尝试了很多事情,但仍然无法正常工作。有人有什么建议吗?

Assuming variable1 and variable2 are the PHP bits you want inserted into the javascript, then 假设variable1variable2是要插入到javascript中的PHP位,则

echo "<a href='javascript: toggle('$variable1', '$variable2')'><label1 for='nameEditor'>Manage</label1></a>";

However, be aware that if either of those variables contain Javascript metacharacters, such as a single quote, you'll be breaking the script with a syntax error (think of it as the same situation as SQL injection). 但是,请注意,如果这些变量中的任何一个包含Javascript元字符(例如单引号),您都将使用语法错误来破坏脚本(将其视为与SQL注入相同的情况)。

To be sure that the variable's contents become legal Javascript, you'd want to do something like: 为确保变量的内容成为合法的Javascript,您需要执行以下操作:

<script type="text/javascript">
    var variable1 = <?php echo json_encode($variable1); ?>;
    var variable2 = <?php echo json_encode($variable2); ?>
</script>

<a href="javascript:toggle(variable1, variable2)...">...</a>

try like this: 尝试这样:

echo "<a href=\"javascript: toggle('variable1', 'variable2')\"><label1 for='nameEditor'>Manage</label1></a>";

you have to escape \\ quotes 您必须转义\\引号

It's because you're mixing your quotes that the browser see. 这是因为您混合了浏览器看到的报价。 Do this: 做这个:

echo "<a href=\"javascript: toggle('variable1', 'variable2')\"><label1 for='nameEditor'>Manage</label1></a>";

If you escape the double quotes (\\"), you'll be fine. The browser itself is seeing '''' (all single quotes), so you need to retain "''" (double,single,single,double) in your html element attribute, irregardless of PHP (except for the escaping). 如果您使用双引号(\\“)进行转义,那会没事的。浏览器本身会看到””(所有单引号),因此您需要保留“””(双,单,单,双)在您的html element属性中,与PHP无关(转义除外)。

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

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