使用 JavaScript 获取服务器路径跨浏览器安全吗?对于 Joomla 模板,我有许多将通过 SCRIPT 标签包含的 JavaScript 文件;这些文件需要服务器路径,例如站点根目录。这是我发现的一些获取服务器路径的 JS 代码:
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 获取服务器路径更好?谢谢。
最佳答案
使用 PHP。您无法使用客户端脚本可靠地检索服务器路径:例如,在 Apache 中使用 mod_rewrite
可以更改 URL 与(本地)服务器路径相关的方式。
关于php - 通过 JavaScript 与 PHP 获取服务器路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4934039/