2013-02-28 20 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'); 
     }); 
    });