如何将HTML的PHP字符串编码为JavaScript函数使用的字符串?
我有以下代码:如何将HTML的PHP字符串编码为JavaScript函数使用的字符串?,javascript,php,iframe,Javascript,Php,Iframe,我有以下代码: <iframe id="uniqueId" frameborder="0" width="100%" height="100%"></iframe> <script> var iframeObject = document.getElementById("uniqueId"); var iframeContent = iframeObject.contentWindow.document; iframeContent.o
<iframe id="uniqueId" frameborder="0" width="100%" height="100%"></iframe>
<script>
var iframeObject = document.getElementById("uniqueId");
var iframeContent = iframeObject.contentWindow.document;
iframeContent.open();
iframeContent.write("<?php echo $htmlString ?>");
iframeContent.close();
</script>;
var iframeObject=document.getElementById(“uniqueId”);
var iframeContent=iframeObject.contentWindow.document;
iframeContent.open();
iframeContent.write(“”);
iframeContent.close();
;
我正在尝试将用户生成的HTML(元数据、
、
、
、
和所有)作为字符串存储在PHP变量$htmlString
中,插入到#uniqueId iframe中,供浏览器/客户端呈现
我真的很难找到正确的方法来安全地转义/编码这个HTML字符串,以便在我编写的JavaScript中使用
在PHP方面,我尝试了
htmlspecialchars()
,htmlentities()
,json\u encode()
,以及$htmlString
上的一些简单的str\u replace()
,但它们都没有达到我需要的效果。有什么我遗漏的吗?我认为您应该将代码保存到文件中,并通过src属性从另一个域加载它
至少jsfiddle.net使用这种方式。我认为您应该将代码保存到文件中,并通过src属性从另一个域加载它
至少jsfiddle.net使用这种方式。感觉自己很笨;问题在于我的JavaScript的语法。一旦我解决了这些问题,
echo-json\u-encode($htmlString)
就成功了;问题在于我的JavaScript的语法。一旦我修复了它们,echo json_encode($htmlString)
就成功了。如何同时使用htmlspecialchars()
和str_replace()
像str_replace(数组(“\r“,“\n”),”,htmlspecialchars($htmlString))
@imtheman,我会在str\u replace中包含反斜杠(“\\”
)。如果转义$htmlString
后的双引号,可能会得到一些奇怪的结果。使用htmlspecialchars()
和str_replace()
像str_replace(数组(“\r“,“\n”),”,htmlspecialchars($htmlString))
@imtheman,我会在str\u replace中包含反斜杠(“\\”
)。如果对$htmlString
后面的双引号进行转义,可能会得到一些奇怪的结果。@jh1711是的,你说得对。我在阅读问题时误解了要求。我已经更新了答案。太好了。我不确定单独的文件是否在所有情况下都有帮助,但至少浏览器不会从不同的源中汇编损坏的Javascript,并尝试运行它们收集的任何内容。@jh1711如果像JSFIDLE一样使用不同的域,则默认情况下无法访问父级的同源策略。所以它一定是安全的。@jh1711是的,你说得对。我在阅读问题时误解了要求。我已经更新了答案。太好了。我不确定单独的文件是否在所有情况下都有帮助,但至少浏览器不会从不同的源中汇编损坏的Javascript,并尝试运行它们收集的任何内容。@jh1711如果像JSFIDLE一样使用不同的域,则默认情况下无法访问父级的同源策略。所以它必须是安全的。