我已经成功地通过 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>
下载.php函数
<html>
<body>
<?php
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
</body>
</html>