2016-11-22 56 views
0

我需要一个HTML模板传递到JavaScript变量在PHP编码和PHP通过HTML为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> 
+0

您可以尝试str_replace函数(阵列( “\ r \ n” ,“\ n”,“\ r”),'',$ html)。 但是你确定这是最好的解决方案吗?将一个html模板传递给PHP中的一个javascript变量;)? –

+0

我不确定:D但我需要我的html模板和我的js在同一个js文件 – TheShun

+0

是的,对不起,这只是在示例中的错误 – TheShun

回答

1

我总是用一个<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; 
+0

看起来不错,可以将多个