2010-09-04 74 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。