我已经成功地通过php从目录中读取了文件,并动态地创建了一个下拉菜单,在这里我可以看到文件的内容。但是,我是通过调用另一个php页面来实现的。有没有办法在同一页中显示文本文件的内容?我知道这可以通过Ajax实现,但是我找不到任何例子。
谢谢

<html>
<head>
<link rel="icon" type="image/png" href="logo.png">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function populateIframe(id,path)
{
    var ifrm = document.getElementById(id);
    ifrm.src = "download.php?path="+path;
}
</script>
<body>
<?php
    //"file_to_be_displayed" is the name of the dropdown
    $selectedfile = @$_POST['file_to_be_displayed'];
    $path ="$selectedfile";
    $content = file($selectedfile);
    $data = implode("<br>",$content);
    echo $data;
?>
<?php
$dirname = "<path>";
$dir = opendir($dirname);
echo '<form name="displayfile" action="print_output_file.php" method="POST" target="_blank">';
echo '<select name="file_to_be_displayed">';
echo '<option value="">Select File</option>';
while(false != ($file = readdir($dir)))
        {
         if(($file != ".") && ($file != ".."))
        {
        echo "<option value=".$file.">$file</option>";
        }
        }
                echo '</select>';
echo '<input type="submit" value="display content of file"/>';
echo '</form>';
?>
</head>
</form>
<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
</body>
</html>

print_output_file.php函数
<html>
<body>
<?php
$myFile =$_POST['file_to_be_displayed'];
$myFile1 ="http://<file path>/"."$myFile";
$lines = file("$myFile1");
$fileString = file_get_contents("$myFile1");
echo nl2br( htmlspecialchars($fileString) );
echo '<br>';
?>
</body>
</html>

download.php函数
<html>
<body>
<?php
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
</body>
</html>

最佳答案

$dirname = "<path>";
$dir = opendir($dirname);
echo '<form  action="" method="" target="">';
echo '<select id="select_file">';
echo '<option value="">Select File</option>';
while(false != ($file = readdir($dir)))
        {
         if(($file != ".") && ($file != ".."))
        {
        echo "<option value=".$file.">$file</option>";
        }
        }
                echo '</select>';
echo '</form>';

JS公司
('#select_file').on('change', function() {
   var file_to_be_displayed = 'file_to_be_displayed='+$(this).val();
   $.ajax({
    type:'POST',
    url: "print_output_file.php",
    data:file_to_be_displayed,
    success:function(data){
        $('#id_where_to_show').html(data);
    }
    });
});

要显示的PHP文件基本相同
<?php
$myFile =$_POST['file_to_be_displayed'];
$myFile1 ="http://<file path>/"."$myFile";
$lines = file("$myFile1");
$fileString = file_get_contents("$myFile1");
echo nl2br( htmlspecialchars($fileString) );
?>

因此,当您选择一个选项时,它将加载到您的文件中。
我希望,我正确地理解了你想要的。。所以没有Iframe和$获得[],
首先在下拉列表中将文件名作为选项输出,在选择将文件传递给ajax时,它将返回内容。你可以玩更多。。。

07-25 22:39
查看更多