使用Jquery和PHP在目录中搜索文件。如果存在,请将其显示在带有下载功能的< a>标签中。搜索文件并在href中下载以供下载
代码大部分适用。但是,我遇到了导致链接多次显示的错误。
使用javascript开始:显示数据表
$('#submitSearch').on('click', function()
{
var voyage = $('#voyageText').val();
$.post('searchVoyages.php', {voyage:voyage}, function(data)
{
var obj = JSON.parse(data);
$('#voyageBody').empty();
var htmlToInsert = obj.map(function (item)
{
return '<tr><td><a href="#" class="voyageFileCall" data-filevoyage="'+item.voyage+'">'+item.voyage+'</a>
<td>'+item.export_import+'</td></tr>';
});
$('#voyageBody').html(htmlToInsert);
// The user submits a search, and the data is returned and displayed
// in a datatable. (image below) The next part is where the user clicks
// the link to open a modal window that display a download link
$('.voyageFileCall').on('click', function(e)
{
e.preventDefault();
var filevoyage = $(this).attr('data-filevoyage');
$.post('fileDownload.php', {filevoyage:filevoyage}, function(data)
{
$('.filelink').empty();
var htmlToInsert = obj.map(function (item)
{
return '<a href="'+data+'" download>"'+data+'"</a>';
});
$('.filelink').html(htmlToInsert);
});
$('#downloadFileModal').modal('show');
}); // end voyageFileCall click
}); // end searchVoyage post
}); // end submitSearch click
后,第一列(即链接)有一个名为.voyageFileCall类,点击后会采取的属性,并张贴到这个过程被称为fileDownload.php。
这里是fileDownload.php样子:
<?php
if(isset($_POST['filevoyage']))
{
$voyage = $_POST['filevoyage'];
$dir = scandir("backup/");
unset($dir[0], $dir[1]);
if(count($dir) > 0)
{
$fileFound = false;
foreach($dir as $file)
{
if((preg_match("/\b$voyage\b/", $file) === 1))
{
$finalLink = 'backup/'.$file;
echo $finalLink; // I think the problem is in this loop
$fileFound = true;
}
}
if(!$fileFound) die("File $voyage doesn't exist");
}
else
{
echo "No files in backup folder";
}
}
?>
所以,当我返回变量$ finalLink,出于某种原因,它会显示该链接的相同的次数返回多少数据在数据表中。
但是,当他们点击链接,和窗口将打开,这是他们所看到的:
在控制台中,我看到:
模式窗口应打开一个单一的链接,用户可以点击d从目录下载文件。但是它似乎显示了相同的链接,但是显示的是从初始搜索返回的数据量。
在这种情况下,初始搜索返回7条记录。当用户点击其中一个链接时,模式会打开7个具有相同文件名的链接。我可以点击每一个,它会下载我的文件。但我只想显示1个链接。
请帮我修复我的代码。我知道它与PHP过程中的foreach循环有关。我只是不知道如何解决它。
谢谢。
看起来很有希望,但我仍然得到相同的结果。有什么想法吗? –
看看更新后的答案 – Nineoclick
我对你的回应感到满意,因为你花时间来帮助我。但是,我仍然得到相同的结果。 :( –