我需要将 html 模板传递给 php 中的 javascript 变量
我尝试了不同的方法,例如 json_encode()、str_replace() addcslashes() 但 javascript 总是抛出意外字符的错误
<?php
$html = file_get_contents('template.html');
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>
<script> var template = "<?php echo escapeJavaScriptText($html) ?>"</script>
最佳答案
我总是使用<script>
标签来保存我的 HTML 模板。这是我从使用 Handlebars JS 中学到的习惯。 http://handlebarsjs.com/
诀窍是type="text/html"
属性,浏览器不知道如何处理它,因此不会显示它,也不会尝试将其作为代码运行。
<script type="text/html" id="Template1">
<p>This is a template</p>
<p>More template stuff</p>
</script>
要访问模板,您可以执行类似的操作
JQuery:
$('#Template1').html()
Javascript:
document.getElementById('Template1').innerHTML;
关于javascript - 对 HTML 进行编码并将其从 PHP 传递到 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40742552/