2014-11-24 54 views
1

我想使用JavaScript获取网站的基本网址。我使用如何使用javascript在服务器上获取网站的URL

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

这是工作mysite.com/project1而不是mysite.com

我该如何检查这两个网址?我必须向网址发送ajax请求。

在此先感谢。

+0

请删除PHP标签,这个问题从根本上与PHP无关。 – seanyt123 2014-11-24 08:51:02

+0

可能重复的[在JavaScript中获取当前URL?](http://stackoverflow.com/questions/406192/get-current-url-in-javascript) – IROEGBU 2014-11-24 08:59:49

回答

0

基地网址应以特殊标记在标题中定义:在现代浏览器

var baseURL = document.baseURI 

或 :

<head> 
<base href="http://example.com/project1/"> 
</head> 

然后你就可以用JavaScript阅读年龄较大

var baseURL = document.getElementsByTagName('base')[0].href 
+0

非常感谢您的解决方案.. – tarangini 2014-11-24 09:09:20

1

这一个应该工作(根据您的 “基础URL” 的定义):

<script> 
 
/** 
 
* Get the parts of an URL. 
 
* 
 
* @param url URL to fetch information from 
 
* @return parts of an URL 
 
*/ 
 
function getURLParts(url) { 
 
    var parser = document.createElement('a'); 
 
    parser.href = url; 
 
    return parser; 
 
} 
 

 
// Show the URL information 
 
var parser = getBaseURL(window.location); 
 
alert(parser.protocol); 
 
alert(parser.host); 
 
alert(parser.hostname); 
 
alert(parser.port); 
 
alert(parser.pathname); 
 
alert(parser.hash); 
 
alert(parser.search); 
 
</script>

+0

这只给出主机位置..但不能达到项目目录.. – tarangini 2014-11-24 08:52:19

+0

见编辑:),现在你可以结合所有的部分。 – 2014-11-24 08:55:19

0

简单地使用窗口的位置属性例如window.location.href

<script> 
 
    alert(window.location.href); 
 
</script>

0

我猜你需要在当前网站的基本URL。从这个answer

pathArray = window.location.href.split('/'); 
protocol = pathArray[0]; 
host = pathArray[2]; 
url = protocol + '//' + host; 
相关问题