Pass a PHP string to a JavaScript variable (and es

2018-12-31 00:22发布

This question already has an answer here:

What is the easiest way to encode a PHP string for output to a JavaScript variable?

I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.

Normally, I would just construct my JavaScript in a PHP file, à la:

<script>
  var myvar = "<?php echo $myVarValue;?>";
</script>

However, this doesn't work when $myVarValue contains quotes or newlines.

14条回答
谁念西风独自凉
2楼-- · 2018-12-31 00:30

If you use a templating engine to construct your HTML then you can fill it with what ever you want!

Check out XTemplates. It's a nice, open source, lightweight, template engine.

Your HTML/JS there would look like this:

<script>
    var myvar = {$MyVarValue};
</script>
查看更多
妖精总统
3楼-- · 2018-12-31 00:34
function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
查看更多
深知你不懂我心
4楼-- · 2018-12-31 00:34

You could try

<script type="text/javascript">
    myvar = unescape('<?=rawurlencode($myvar)?>');
</script>
查看更多
墨雨无痕
5楼-- · 2018-12-31 00:40

The paranoid version: Escaping every single character.

function javascript_escape($str) {
  $new_str = '';

  $str_len = strlen($str);
  for($i = 0; $i < $str_len; $i++) {
    $new_str .= '\\x' . sprintf('%02x', ord(substr($str, $i, 1)));
  }

  return $new_str;
}

EDIT: The reason why json_encode() may not be appropriate is that sometimes, you need to prevent " to be generated, e.g.

<div onclick="alert(???)" />
查看更多
余生请多指教
6楼-- · 2018-12-31 00:43
<script>
var myVar = <?php echo json_encode($myVarValue); ?>;
</script>

or

<script>
var myVar = <?= json_encode($myVarValue) ?>;
</script>
查看更多
其实,你不懂
7楼-- · 2018-12-31 00:43

You can insert it into a hidden DIV, then assign the innerHTML of the DIV to your JavaScript variable. You don't have to worry about escaping anything. Just be sure not to put broken HTML in there.

查看更多
登录 后发表回答