簡體   English   中英

為javascript函數轉義php變量中的所有引號和重音符號

[英]escape all quotes and accents in php variable for javascript function

我有這個代碼:

<html>
<?php
$var="\'quotes\" àccènts";  //  'quotes" àccènts
?>
<button onclick="fun('<?php echo $var ?>');">click me</button>
</html>

但是當我點擊時,我在控制台中得到“Uncaught SyntaxError:Invalid or unexpected token”

我試過這個:

<button onclick="fun('<?php echo $var ?>');">click me</button>
<?php
function escape($var)
{
    $var=str_replace("'","\\'",$var);
    $var=str_replace("\"","&quot;",$var);
    $var=trim(preg_replace("/\s+/"," ",$var));
    return $var
}
?>

但后來口音變成了未知的角色,我怎樣才能在內聯html中解決這個問題?

你可以解決它。 例如

<script>
function fun2()
{
   return fun(<?php echo json_encode($var); ?>);
}
</script>

<button onclick="fun2();">click me</button>

如果你想多次這樣做,例如在一個字符串列表的循環中,你也可以解決它(除非你想破壞原來的php字符串),通過:

<script>
// assuming an array of string variables with quotes and accents
var strings = <?php echo json_encode($strings); ?>;
</script>

<?php for($i=0,$l=count($strings); $i<$l; $i++) { ?>
<button onclick="fun(strings[<?php echo $i; ?>]);">Click me!</button>
<?php } ?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM