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

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

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

例子也可能改变。


当前回答

这将得到base url

var baseurl = window.location.origin+window.location.pathname;

其他回答

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

更简单的答案在这里,window。location。href = window。location。origin;

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

    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;
    }

这条会帮助你……

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

我认为这对你很有用:

var base_url = window.location.origin;

var host = window.location.host;

var pathArray = window.location.pathname.split( '/' );