2011-02-08 56 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