开发者

Php echo javascript with variables

开发者 https://www.devze.com 2023-02-07 05:45 出处:网络
have a question about a php echoing script that has a link to a javascript with some variables. I need to know the format for the echo so it will work properly. Could anyone shed any light on this? My

have a question about a php echoing script that has a link to a javascript with some variables. 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 hre开发者_Go百科f='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?


Assuming variable1 and variable2 are the PHP bits you want inserted into the javascript, then

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).

To be sure that the variable's contents become legal Javascript, you'd want to do something like:

<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).

0

精彩评论

暂无评论...
验证码 换一张
取 消