使用JS替换整个页面时出错 [英] Error when replace whole page using JS

查看:117
本文介绍了使用JS替换整个页面时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容为html的php变量:

I have a php variable with content is html:

当我使用Javascript时:

When I using Javascript:

document.body.innerHTML.replace("<?php echo $content ?>");

要替换整个页面,它会显示错误:

to replace whole page, it say error:

和jQuery是相同的错误:

and jQuery is same error:

jQuery('html').html("<?php echo $content ?>");

我可以通过任何方式做到这一点,JS和PHP解决方案都可以.

There any way I can do that, JS and PHP solution are ok.

推荐答案

似乎引号和特殊字符更少,而换行符更多. 您可以使用json来防止出现所有这些字符.

It seems to be less about quotes and special characters and more about newlines. You can use json to protect against all these character occurrences.

document.body.innerHTML = <?=json_encode($html)?>;

这在我的服务器上有效:

This works on my server:

<?php
$html = <<<HTML
<span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span>
<a href="http://google.com">Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</a>
<strong>When an unknown printer took a galley of type and scrambled it to make a type specimen book</strong>
HTML;
?>

<html>
    <body>blah</body>
    <script>
        document.body.innerHTML = <?=json_encode($html)?>;
    </script>
</html>


当然,如果您在脚本的前面声明了$html = json_encode($html);,则只能使用document.body.innerHTML = <?=$html?>;.


Of course, you can just use document.body.innerHTML = <?=$html?>; if you declare $html = json_encode($html); earlier in your script.

这篇关于使用JS替换整个页面时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆