【问题标题】:escape all quotes and accents in php variable for javascript function为javascript函数转义php变量中的所有引号和重音符号
【发布时间】:2019-09-25 03:55:12
【问题描述】:

我有这个代码:

<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
}
?>

但是后来重音变成了未知字符,我该如何在 inline html 中解决这个问题?

【问题讨论】:

  • 使用ajax返回你想要的值——混合JS和PHP总是一个坏主意
  • 请解释为什么你需要内联 html 才能工作,如果不破坏原始字符串,就不可能在 onclick 属性中内联它,但如果你充分解释你的用例和需要,也许可以找到一种解决方法对于内联html

标签: javascript php escaping quotes


【解决方案1】:

您可以解决它。例如

<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 } ?>

【讨论】:

  • 我试过但同样的错误:
  • @Miky,这不是我的回答所建议的。你写的不行,我写的会
  • @NikosM.我需要一个 html 内联解决方案
  • @Miky 为什么这不适合你?请解释
猜你喜欢
  • 2011-04-18
  • 2012-07-28
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 2013-03-30
相关资源
最近更新 更多