首页 > 解决方案 > 如果文件存在于服务器中,则显示和隐藏按钮 (href=)

问题描述

我尝试编辑一个类似的解决方案,但它没有达到预期的效果。我不确定我的编码可能是错误的并且我使用的是 html。如果文件存在,有没有办法隐藏按钮(href =)然后显示它是否找不到?谢谢你!

参考:链接

<button type="button" id="test_btn" style="display: none;">Download</button>

<script type="text/javascript">
    $(document).ready(function () {
        checkFile();

        function checkFile() {
            $.ajax({
                url: '/path/to/file_checker.php',
                type: 'GET',
                success: function (data) {
                    if (data === "deleted") { 
                        $('#test_btn').show();
                    }
                    else {
                        $('#test_btn').hidden();
                    }
                }
            });
        }
    }
</script>  

然后您的文件检查器 php 可能与您所拥有的类似:

if (file_exists("/aaa/file.txt")) {
    echo "exists";
}
else {
    echo "deleted";
}

标签: phpcssdisplay

解决方案


另一种方法是向用户提供现有文件的列表,并允许他们从列表中进行选择。

<?php
// Initialize an empty array
$files = [];

// Get all the files in a directory (this will also return directories)
foreach (glob('*') as $f) {

        // If the item is a file, add it to the files array
        if (is_file($f)) {
                $files[] = $f;
        }
}
?>

<!-- Create a select statement with the files that exist -->
<select id="files">
<!-- Placeholder -->
<option disabled selected>Select file</option>

<!-- Loop through all the files and create options for them -->
<?php foreach ($files as $f) : ?>
<option><?= $f ?></option>
<?php endforeach ?>
</select>

<!-- The button would run the download using the selected file as the source (additional JavaScript required) -->
<button id="go">Download</button>

推荐阅读