2011-02-08 61 views
2

使用JavaScript獲取服務器路徑時跨瀏覽器安全嗎?對於Joomla模板,我有大量的JavaScript文件將通過SCRIPT標籤包含在內;這些文件需要服務器路徑,例如站點根。下面是一些JS代碼,我發現它獲取服務器的路徑:通過JavaScript與PHP獲取服務器路徑

var hash = self.location.hash //  Sets or retrieves the subsection of the href property that follows the number sign (#). 
var host = self.location.host // Sets or retrieves the hostname and port number of the location or URL. 
var hostname = self.location.hostname // Sets or retrieves the host name part of the location or URL. 
var href = self.location.href  // Sets or retrieves the entire URL as a string. 
var pathname = self.location.pathname // Sets or retrieves the path and file name associated with a URL.  
var port = self.location.port  // Sets or retrieves the port number associated with a URL. 
var protocol = self.location.protocol // Sets or retrieves the protocol portion of a URL. 

alert('hash: ' + hash + '\n' + 
    'host: ' + host + '\n' + 
    'hostname: ' + hostname + '\n' + 
    'href: ' + href + '\n' + 
    'pathname: ' + pathname + '\n' + 
    'port: ' + port + '\n' + 
    'protocol: ' + protocol); 

以上的JavaScript會返回此:

hash: #panel-1 
host: localhost:8090 
hostname: localhost 
href: http://localhost:8090/joomla/#panel-1 
pathname: /joomla/ 
port: 8090 
protocol: http 

在Joomla網站將在許多瀏覽器,平臺和設備上運行。上述JS代碼是否適合這些場景,還是使用PHP來獲取服務器路徑更好?謝謝。

回答

3

使用PHP。使用客戶端腳本無法可靠地檢索服務器路徑:例如,在Apache中使用mod_rewrite可以更改URL與(本地)服務器路徑相關的方式。

+0

啊......不知道。這是有道理的,所以PHP是更可靠的方法。謝謝。 – Alex 2011-02-08 14:15:23

0

服務器端(PHP)效果更好,因爲如果客戶端禁用JavaScript會怎麼樣。當然,不提及服務器重寫等

+0

在這種情況下,代碼將用於通過SRC屬性包含的SCRIPT文件中。因此,如果客戶端腳本被禁用,整個文件將不會被調用,因此這一點將是沒有意義的。 – Alex 2011-02-08 14:14:18