简体   繁体   English

将Javascript代码存储在PHP变量中?

[英]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: 我想将JavaScript代码存储在PHP变量中,以便将其多次注入到我的主代码中:

<?php

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

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

?>

In Google Chrome I can read this source code: 在Google Chrome浏览器中,我可以阅读以下源代码:

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

So I noticed this: 所以我注意到了这一点:

"hello" world" should be "hello world" "hello" world"应该是"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传递到js,即:

<?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: 您需要在HTML属性值中转义" to &quot; 。还需要用双引号(不得编码)分隔属性值,因为它包含空格,如下所示:

(Also, personally I wouldn't use PHP's <<< for strings) (另外,我个人不会使用PHP的<<<作为字符串)

$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; 尝试添加&nbsp; to change space in your code. 更改代码中的空间。 and DONE! 并做了!

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

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