2010-09-04 73 views
37

我目前正在設置window.location.pathname屬性以將用戶重定向到相對URL。新的URL有參數,這樣的JavaScript的線路是這樣的:設置JavaScript window.location

window.location.pathname = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1) + 'myPage.xhtml?u=' + selected_user.Username; 

這是成功的在Firefox,Chrome的但是編碼問號「%3F」和隨後失敗的請求。

我不確定我是否正確使用window.location。我是否需要使用window.location的屬性,如pathname或href?我發現只要設置了一個屬性,位置就會重新加載,所以例如搜索和路徑名屬性不能單獨設置。可以直接設置window.location嗎?我只需要用參數設置一個相對URL。

回答

56

pathname和許多location其他屬性和環節反映URL的唯一部分

http: //www.example.com/path/to/example.html?param1=2&param3=4#fragment 
^protocol^hostname  ^pathname   ^search   ^hash 

正如你所看到的,URL的?...部分不是pathname的一部分;編寫一個包含?location.pathname的值是沒有意義的,因爲URL的這部分不能包含問號。 Chrome正在通過將字符編碼爲一個序列來糾正您的錯誤,這意味着一個字面問號,該字符不會終止pathname

這些屬性非常適合將URL分解爲其組成部分供您處理,但在這種情況下您可能不希望寫入它們。相反,寫信給location.href。這代表了整個URL,但是寫一個相對URL是完全正確的;這將制定出相對於當前值,所以其實沒有必要讀,並在所有拆分pathname

location.href= 'myPage.xhtml?u='+encodeURIComponent(selected_user.Username); 

注意URL編碼的。如果用戶名可以包含除字母數字以外的其他字符,則可能需要使用此字符來阻止那些破壞參數的字符。在將它們放入URL的一部分之前,始終對任意字符串進行URL編碼。

+1

感謝您的詳細解釋。我更改了我的代碼以使用href屬性,並且還調用encodeURIComponent()。 – Mark 2010-09-04 20:16:50

+1

請注意[對於大多數情況](http://stackoverflow.com/questions/6725890/window-location-host-vs-window-location-hostname-and-cross-browser-compatibility),你想使用' location.host'而不是'location.hostname'。總之,這是因爲你的代碼在某些時候可能運行在80以外的端口上的服務器上。 – 2013-09-28 21:12:44

+0

請注意,在源代碼爲iframe的(罕見)情況下,它需要執行window.parent.location .. ... – 2015-07-15 13:29:31

11

嘗試設置location.href屬性而不是window.location.pathname

+0

只是'window.location = ...'已經足夠了 – vsync 2014-08-12 09:45:26

+0

給'window.location'賦值會導致TypeScript中的錯誤。我想分配給'window.location.href'是更好的選擇。 – mvermand 2016-12-13 09:26:52

7

使用window.location.href被認爲是最安全的方式設置的URL。我認爲這應該修復編碼問題。

window.location.href = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1) + 'myPage.xhtml?u=' + selected_user.Username; 

如果這沒有幫助,請顯示示例URL。