如何使用PHP和JavaScript列出服务器上的所有文件夹
在我的Web服务器上,我有几个目录,其中包含以下文件:如何使用PHP和JavaScript列出服务器上的所有文件夹,php,javascript,prototypejs,directory-listing,Php,Javascript,Prototypejs,Directory Listing,在我的Web服务器上,我有几个目录,其中包含以下文件: a文件夹/file.xml 另一个文件夹/file.xml stillother/file.xml 这些文件包含我想在地图上显示的一些位置的信息(使用openlayers),因此我需要JS格式的文件。问题是,我不知道这些文件夹叫什么,它们有多少个,所以我需要它们的列表 我需要这样的东西: for each (folder as f) map.showLocations(f/file.xml) 这怎么可能呢 我搜索了解决方案,但
- a文件夹/file.xml
- 另一个文件夹/file.xml
- stillother/file.xml
for each (folder as f)
map.showLocations(f/file.xml)
这怎么可能呢
我搜索了解决方案,但只找到了客户端上的文件和文件夹。
我使用的是prototype js,可以使用PHP。如果您在PHP变量
$directories
中列出您的目录,您可以echo
到类似的页面
echo '<script>var Directories = '.json_encode($directories).';</script>';
另一种选择是让AJAX请求为您完成(我在本例中使用jQuery,因为我不知道原型,但它应该大致相同)
你的PHP代码应该是这样的
<?php
*** iterate over the directories and save them into an array ***
echo json_encode($directories);
exit();
?>
大约两个小时前,为了我的工作,我不得不这么做。我用了一种新的方法 如果您只是想将数据转换成JavaScript,那么这个UI插件可能有点过头了,但它包含的源代码将返回JSON,其中包含一个路径列表,您可以通过调用jQuery.ajax请求来获取该路径 JavaScript(jQuery):
$.ajax({
type: "POST",
data: {
dir : '/your_directory'
}
contentType: "application/json; charset=utf-8",
url: 'getDirectories.php',
success: function(d) {
//do something with the data
console.dir(d.directories); //d.directories will be an array of strings
}
});
PHP
//return a JSON object with directories
这是其他人都在谈论的PrototypeJS版本
new Ajax.Request('getdirectories.php',{
method : 'post',
onSuccess : function(result){
//result.responseJSON is the JSON object
var dirs = result.responseJSON;
dirs.each(function(item){
map.showLocations(item+'/file.xml');
});
});
那有点危险。您并不真的希望浏览器搜索服务器目录。为什么不使用一个返回所有文件的web服务呢?您需要用php而不是javascript来实现这一点。JS在客户端运行,您的文件在服务器上。无法通过客户端javascript完成。@JHnet只需让javascript代码向服务器端PHP脚本发出Ajax请求,该脚本获取并返回信息。您可以将PHP的结果作为隐藏层输出到文档中,甚至直接将其注入javascript。Ajax也是一种选择。好的,谢谢!我以前从未使用过ajax,但总有第一次:)必须检查原型文档的exakt语法,但感谢您提供的一般方法!好的,谢谢!我以前从未使用过ajax,但总有第一次:)必须检查原型文档的exakt语法,但感谢您提供的一般方法!
//return a JSON object with directories
new Ajax.Request('getdirectories.php',{
method : 'post',
onSuccess : function(result){
//result.responseJSON is the JSON object
var dirs = result.responseJSON;
dirs.each(function(item){
map.showLocations(item+'/file.xml');
});
});