gpt4 book ai didi

php - 使用引号和换行符对 PHP 变量进行编码以传递给 Javascript 函数(然后反转编码)

转载 作者:可可西里 更新时间:2023-11-01 12:54:51 26 4
gpt4 key购买 nike

假设您有一个名为 $description 的 PHP 变量,其值如下(包含引号和换行符):

Tromp L'oeil Sheath Dress

You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.

您想将此变量的内容传递给一个 Javascript 函数,该函数将该值写入文本类型的 INPUT。

你会怎么做?我试过这个:

$description = htmlspecialchars ( $product->description, ENT_QUOTES );

但是,我收到一个 JS 错误。我也试过这个:

$description = rawurlencode ( $product->description );

这样编码值:

Michael%20Kors%0A%0ATromp%20L%27oeil%20Sheath%20Dress%0A%0AYou%20will%20certainly%20%22trick%20the%20ey%22%20of%20many%20in%20this%20gorgeous%20illusion.%20Add%20it%20to%20your%20fall%20wardrobe%20before%20it%20disappears.%0A%0AAvailable%20in%20Black%2FNude

这个值可以作为 JS 变量传递,但我不知道有一个 JS 函数可以完全反转 PHP rawurlencode。

是否有一对匹配的函数可用于在 PHP 中对变量进行编码以允许将其传递给 JS 函数——然后在 JS 中反转编码以便获得 PHP 变量的原始值?

编辑:为了澄清问题并回复评论,这里有一些测试代码:

<?php
$str =<<<EOT
Tromp L'oeil Sheath Dress

You will certainly "trick the eye" of many in this gorgeous illusion. Add it to your fall wardrobe before it disappears.
EOT;
echo 'here is the string: <pre>' . $str . '</pre>';
?>

<script type="text/javascript">
<?php
// this does not work with JS as i get an unterminated string literal if i just use addslashes in the following commented-out line
// echo 'alert(\'' . addslashes($str) . '\');';

// this works with JS (the alert activates) but how do i un-rawurlencode in JS?
// echo 'alert(\'' . rawurlencode($str) . '\');';

// this does not work with JS, because of the line breaks
echo 'alert(\'' . htmlspecialchars ($str, ENT_QUOTES) . '\');';
?>
</script>

最佳答案

最简单的是使用 json_encode()

关于php - 使用引号和换行符对 PHP 变量进行编码以传递给 Javascript 函数(然后反转编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com