开发者

Getting server paths via JavaScript vs. PHP

开发者 https://www.devze.com 2023-02-09 10:53 出处:网络
Is it cross-browser safe to use JavaScript to fetch server paths? For a Joomla template, I have a number of JavaScript files that will be included via SCRIPT tags; these files need server paths, such

Is it cross-browser safe to use JavaScript to fetch server paths? For a Joomla template, I have a number of JavaScript files that will be included via SCRIPT tags; these files need server paths, such as the site root. Here's some JS code that I found which gets server paths:

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 pr开发者_开发问答otocol 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);

The above JavaScript returns this:

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

The Joomla site will run across many browsers, platforms, and devices. Will the above JS code work well for these scenarios or is it better to use PHP to fetch server paths? Thanks.


Use PHP. You can't reliably retrieve the server paths using client-side scripting: e.g., using mod_rewrite in Apache one can change the way URLs relate to (local) server paths.


Server side (PHP) works better because what if the client disables JavaScript. Of course without mentioning server rewrite and etc

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号