使用javascript获取主机名(基本URL)
获取主机名的方法太多,如下代码所示:使用javascript获取主机名(基本URL),javascript,jquery,Javascript,Jquery,获取主机名的方法太多,如下代码所示: window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80 window.location.hostname // you'll get sub.domain.com window.location.protocol // you'll get http: window.location.port // you'll get 8080 or 80 window.loc
window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80
window.location.hostname // you'll get sub.domain.com
window.location.protocol // you'll get http:
window.location.port // you'll get 8080 or 80
window.location.pathname // you'll get /virtualPath
就我而言,我想要一些不同的东西。例如:
我的QA站点名称是example.com/testsite/index.html
我的产品站点名是example.com/index.html
使用上述方法获取主机名时出现的问题是,它仅返回如下主机名:example.com
但是对于QA,我需要返回example.com/testsite
对于PROD,我需要返回example.com
是否可以使用单一代码?提前感谢。要实现您的要求,您需要检查
窗口.location.hostname
,以及窗口.location.pathname中的第一个文件夹。大概是这样的:
function getPath() {
var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : '';
return window.location.hostname + folder;
}
使用window.location.hostname强>
示例:
页面URL为
适用于产品和质量保证的最佳方法
var BASE_URL = window.location.href;
BASE_URL = BASE_URL.split("testsite");
if (BASE_URL.length > 1)
{
BASE_URL = BASE_URL[0];
BASE_URL = BASE_URL + 'testsite';
} else{
BASE_URL = window.location.origin;
}
你已经有了所有你需要的信息window.location.hostname+window.location.pathname
我不明白问题出在哪里:/谢谢你的评论,但我不知道我是在代码端的QA还是PROD。要操作实际路径,您问题的标题并不代表您要回答的问题Tanks@Rory,但我的站点下的文件夹没有类似“testsite”的固定名称。您的问题说有…?好的,但只需将字符串更改为应该的名称即可。逻辑是相同的,但是如何在响应中获取/testsite
路径呢?感谢@Satinder的响应,但是如果是QA'(localhost/testsite/test/form.html)”,在这种情况下它将起作用。但是PROD'(localhost/test/form.html)会给出错误的最终结果
var getHostname = window.location.hostname; //localhost
var getPathName = window.location.pathname // Default2.aspx
var split_PathName = String(getPathName.split("/"));
var FinalURL = getHostname + "/" + split_PathName[1]
var BASE_URL = window.location.href;
BASE_URL = BASE_URL.split("testsite");
if (BASE_URL.length > 1)
{
BASE_URL = BASE_URL[0];
BASE_URL = BASE_URL + 'testsite';
} else{
BASE_URL = window.location.origin;
}