假設您有一個名爲$ description的PHP變量,其值爲以下值(包含引號和換行符):編碼帶引號和換行符的PHP變量以傳遞給Javascript函數(然後反轉編碼)
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.
您想將此變量的內容傳遞給一個將該值寫入文本類型的INPUT的Javascript函數。
你會如何做到這一點?我試過這個:
$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>
爲什麼不直接呼應的實際變量轉化爲JavaScript變量?所有你需要擔心的是單引號和/或雙引號,可以通過'addslashes()'方便地修復... – animuson 2010-07-13 18:10:36
你從PHP獲取這個到js的方法是什麼?它只是迴應到腳本標記分配js變量和執行後輸出html中的某個地方? – DeaconDesperado 2010-07-13 18:10:56
你可以對什麼是「不工作」與用htmlspecialchars更具體? – Savageman 2010-07-13 18:11:02