【问题标题】:how to display multiple line file contents in javascript如何在javascript中显示多行文件内容
【发布时间】:2010-10-28 00:44:04
【问题描述】:

我有一个页面,单击按钮会在页面的文本区域中显示文件中的文本内容

javascript函数

function displayOutput()
    {
    <?php   
        $logfile = "hello";  
        $fh = fopen($logfile, 'r');  
        $size = filesize($logfile);  
        if($size == 0)  
                {  
            echo "Log file is getting generated";  
                }  
        else{  
            $theData = fread($fh, $size);  
            $data = trim($theData);  
            }  
        fclose($fh);  
    ?>  
    var html = "<?php echo $data; ?>";  
    document.form.text1.value = html;  
}  

使用此功能,只有当文件包含单行时,我才能正确显示文件内容。

我想在 textarea 中显示多行。我尝试删除 $data = trim($theData) 但没有看到任何输出。如果我回显 $theData 我能够看到所有文件内容,但在一行中。我也尝试过使用 while(!feof(filename)) 但即使这样也没有用。

如何使用 javascript 在新行上显示文件的所有内容?

【问题讨论】:

    标签: php javascript html file


    【解决方案1】:

    试试这个:

    <?php   
        $logfile = "hello";  
    ?>
    function displayOutput()
    {
        var html = <?php
            echo filesize($logfile)
                ? json_encode(file_get_contents($logfile))
                : '"Log file is getting generated"'; 
            ?>;
        document.form.text1.value = html;
    }
    

    编辑以包含filesize=0 条件

    【讨论】:

    • 这看起来基本上是你想要的,但由于你是直接设置文本,你不会想要json_encode(); 输出。不过,您可能希望将其包装在一个字符串中,并且可能需要转义文件内容中的任何字符串字符。
    • json_encode 当你传递一个 php 字符串时返回一个 js 字符串(我刚刚测试过)
    • 我还想在每次单击按钮时重新加载文件。由于它是一个日志文件,因此添加了新内容。我可以这样做吗?
    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多