2013-02-28 19 views
0

在我的web服务器的服务器上的所有文件夹我有几个目录,在他们的文件,如:如何列出与PHP和JavaScript

  • afolder/file.xml
  • anotherfolder/file.xml
  • stillanother/file.xml

这些文件包含有关我想要在地图上显示的某些位置的信息(使用openlayers),所以我需要JS中的文件。问题是我不知道文件夹被称为什么,有多少人在那里,所以我需要一个列表。

我需要的是这样的:

for each (folder as f) 
    map.showLocations(f/file.xml) 

怎么能这样做?

我搜索了解决方案,但我发现的所有内容都是关于客户端的文件和文件夹。 我正在使用原型js,并有可能使用PHP。

+5

这是一个有点危险。你真的不希望你的浏览器搜索服务器目录。为什么不能有一个返回所有文件的Web服务? – 2013-02-28 20:46:46

+7

你会想在php中做这个,而不是javascript。 JS在客户端上运行,你的文件在服务器上。 – 2013-02-28 20:48:08

+0

你正在服务器上运行JavaScript? – 2013-02-28 20:49:06

回答

1

如果你在一个PHP变量$directories列出您的目录,你可以echo页面类似

echo '<script>var Directories = '.json_encode($directories).';</script>'; 

现在你有你的页面内的JavaScript变量,您可以遍历,做你的魔术

for (dir in Directories) { 
    map.showLocations(Directories[dir]/file.xml); 
} 

另一种选择是有一个Ajax请求你做它(我使用jQuery在这个例子中,因为我不知道原型BU它应该是大致相同)

$.getJSON('directories.php', function(data) { 
    $.each(data, function(index, value) { 
    map.showLocations(value+'/file.xml'); 
    }); 
}); 

和你的PHP代码应该是这样的

<?php 
    *** iterate over the directories and save them into an array *** 
    echo json_encode($directories); 
    exit(); 
?> 
+1

好的谢谢!我以前从未使用ajax,但始终有第一次:)必须检查exakt语法的原型文档,但感谢您使用一般方法! – JHnet 2013-02-28 21:12:49

0

我不得不为我的工作做约2小时前。我用了一个jQuery plugin from A Beautiful Site called jQuery File Tree

如果您只是想将数据转化为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 
+0

好的谢谢!我以前从未使用ajax,但始终有第一次:)必须检查exakt语法的原型文档,但感谢您使用一般方法! – JHnet 2013-02-28 21:13:17

0

这里是每个人都在谈论的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'); 
     }); 
    });