简体   繁体   中英

store Javascript code in PHP variable?

I would like to store JavaScript code in a PHP variable, in order to inject it multiple times into my main code:

<?php

$PASSME = <<<PASSME
alert("hello world");
PASSME;

echo "<a onclick=$PASSME >Click here</a>";

?>

In Google Chrome I can read this source code:

<a onclick="alert("hello" world");>Click here</a>

So I noticed this:

"hello" world" should be "hello world"

What am I doing wrong?

NB: I am actually working on a more complex project. I tried to make an example in order to understand how to correctly do it.

As I commented you used double quoetes in double quotes, use single quotes instead:

<?php

$PASSME = <<<PASSME
alert('hello world');
PASSME;

echo "<a onclick=\"$PASSME\" >Click here</a>";

?>

This will result in correct code:

<a onclick="alert('hello world');">Click here</a>

When having a lot of code, just pass variables from php to js, ie:

<?php

$PASSME = <<<PASSME
var message = 'hello world'
PASSME;
?>
<script>
<?= $PASSME; ?>
</script>
<?
echo "<a onclick=\"alert(message)\">Click here</a>";
?>

The problem is that your attribute value contains space characters and is not delimited with quote characters.

<?php
  $html_safe_passme = htmlspecialchars($PASSME, ENT_QUOTES);
?>
<a onclick="<?php echo $html_safe_passme; ?>">Click here</a>

You need to escape the " to &quot; in the HTML attribute value. You also need to delimit the attribute value with double-quotes (which mustn't be encoded) because it contains spaces, like so:

(Also, personally I wouldn't use PHP's <<< for strings)

$passme = "alert(&quot;hello world&quot;);";

echo "<a onclick=\"$passme\">click here</a>";

像这样尝试,用单引号引起来:

alert('hello world');

Use following (You missed Quotes around variable)

 <?php

$PASSME = <<<PASSME
alert("hello world");
PASSME;

echo "<a onclick='".$PASSME."' >Click here</a>";

?>
<?php

$PASSME = "alert('hello&nbsp;world');";

echo "<a onclick=". $PASSME . " >Click here</a>";

?>

try to add &nbsp; to change space in your code. and DONE!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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