为什么document.write + echo不起作用?

Aga*_*oxi 2 javascript php document.write

可能重复:
如何将javascript变量放入php echo中

我有PHP的问题.我想在JavaScript中使用PHP变量.但是,它不起作用!$doccontent只显示一次!这是Test.php(例如,给出页面参数Test.html):

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <?php
        $page = $_GET["page"];
        $doc = new DOMDocument();
        $doc->loadHTMLFile($page);
        $doc->formatOutput = true;
        $contentnode = $doc->getElementById('content');
        $doccontent = new DOMDocument();
        $doccontent->appendChild($doccontent->importNode($contentnode, true));
        $doccontent = $doccontent->saveHTML();
        ?>
    </head>
    <body>
        <?php
            echo $doccontent;
        ?>
        <script type="text/javascript">
            document.write("<?php echo $doccontent;?>");
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是Test.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Hey</title>
        <link rel="stylesheet" type="text/css" href="Edit.css">
    </head>
    <body>
        <button id="admin"><a href="Edit.php?page=Edit.html">Edit</a></button>
        <h1>Automatica</h1>
        <div id="content">
            <h2>Header 1.1</h2>
            <p>Test</p>
            <h3>Header 1.1.1</h3>
            <p>Test</p>
            <h3>Header 1.1.2</h3>
            <p>Test</p>
            <p>Test</p>
            <h4>Header 2.0.0.1</h4>
            <p>Test</p>
        </div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 5

$doccontent几乎可以肯定包含"字符和新行,其中任何一行都会破坏由"字符分隔的JS字符串文字.

json_encode给定一个字符串作为输入,PHP 函数将输出一个JS字符串文字.您可以使用它而不是回显原始数据.(切记不要"在生成的字符串文字周围添加额外的字符).