javascript - 使用 PHP 和 Ajax 返回文件地址
问题描述
我有这样的 PHP 文件:
<?php
function getDirContents($directories, &$results = array()){
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents([$path], $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
return $results;
}
echo json_encode(getDirContents($_POST['directories']));
我有一个像这样的 ajax 调用命中上面的 PHP 文件:
function getURLs(directories) {
$.ajax({
type: 'POST',
url: 'https://localhost/preload.php',
data: {id: "testdata", directories: directories},
dataType: 'json',
cache: false,
success: function(result) {
// here is the result
console.log(result);
},
});
}
正如您使用上面的代码所看到的,我们能够检索服务器上给定文件夹数组的所有文件地址,例如,如果文件夹中有两个文件名为1-1.mp3
和sample.png
,https://localhost/sources/folder
那么我们可以从 Ajax 调用中获取:
getURLs([sources/folder]);
// returns : ['https://localhost/sources/folder/1-1.mp3', 'https://localhost/sources/folder/sample.png']
如果你给它一个要搜索的文件夹数组,这个函数就可以正常工作,但是如果你给它一个文件地址,它就不会返回结果,这就是问题所在
getURLs([sources/folder/1-1.mp3]); //returns nothing
如果当然存在,我希望上述函数也返回文件地址:
'https://localhost/sources/folder/1-1.mp3'
所以最终函数将返回服务器上存在的文件和文件夹数组的地址。(我们想添加文件搜索功能,因为文件夹搜索工作正常)
我们如何修改 PHP 代码来做到这一点?
解决方案
推荐阅读
- python - 如何修复''在位置 2 没有重复的内容''
- ansible - 为什么 Ansible 会忽略我的库存文件?
- django - 权限类装饰器被忽略。“未提供身份验证凭据”响应
- sql - PostgreSQL group_concat 行作为 json
- ios - FaceID动画完成后如何准确回调?
- python-3.x - 从网页中提取 URL 链接
- java - Java getter setter 无法存储值
- amazon-cloudfront - 使用 aws cli 在 extsting 云端分发中添加额外的来源和行为
- mongodb - 快速查询MongoDB的数据结构设计
- swift - 任何人都可以帮助我如何从给定的示例中获得价值,因为我是 swift 新手