douyi6755 2012-12-16 14:03
浏览 82
已采纳

为什么document.write + echo不起作用? [重复]

Possible Duplicate:
how to put javascript variable in php echo

I have a problem with PHP. I want to use a PHP variable in JavaScript. However, it does not work! $doccontent is displayed just once! Here is Test.php (the page parameter is given, e.g. 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>

and here is 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>
  • 写回答

1条回答 默认 最新

  • dpo15099 2012-12-16 14:06
    关注

    $doccontent almost certainly contains both " characters and new lines, either of which will break a JS string literal delimited by " characters.

    The PHP json_encode function will, given a string as input, output a JS string literal. You could use that instead of echoing the raw data. (Remember not to add extra " characters around the generated string literal).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)