2014-11-24 51 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; 
相關問題