在joomla php中,我可以使用$this->baseurl来获得基本路径,但我想在jquery中获得基本路径。

基本路径可以是以下示例中的任意一个:

http://www.example.com/
http://localhost/example
http://www.example.com/sub/example

例子也可能改变。


当前回答

容易

$('<img src=>')[0].src

生成一个带有空src-name的img会迫使浏览器自己计算base-url,不管你是否有/index.html或其他什么。

其他回答

这条会帮助你……

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
var getUrl = window.location;
var baseurl = getUrl.origin; //or
var baseurl =  getUrl.origin + '/' +getUrl.pathname.split('/')[1]; 

但你不能说CodeIgniter(或php joomla)的baseurl()将返回相同的值,因为可以更改这些框架的.htaccess文件中的baseurl。

例如:

如果你在本地主机上有一个。htaccess文件:

RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

$this->baseurl()将返回http://localhost/CodeIgniter/

拆分并加入URL:

const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"

几乎和Jenish的答案一样,但更短一点。

如果有人想把它分解成一个非常健壮的函数

    function getBaseURL() {
        var loc = window.location;
        var baseURL = loc.protocol + "//" + loc.hostname;
        if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
        // strip leading /
        var pathname = loc.pathname;
        if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
        var pathParts = pathname.split("/");
        if (pathParts.length > 0) {
            for (var i = 0; i < pathParts.length; i++) {
                if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
            }
        }
        return baseURL;
    }