45

我目前正在设置 window.location.pathname 属性以将用户重定向到相对 URL。新 URL 具有参数,因此 JavaScript 行如下所示:

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 的属性,例如路径名或 href?我发现一旦我设置了一个属性,就会重新加载位置,例如,搜索和路径名属性不能单独设置。可以直接设置window.location吗?我只需要设置一个带参数的相对 URL。

4

3 回答 3

65

pathname和链接的许多其他属性location仅反映URL 的一部分:

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

如您所见,?...URL 的一部分不是pathname;的一部分。?写一个包含to的值是没有意义的location.pathname,因为 URL 的那部分不能包含问号。Chrome 通过将字符编码为表示文字问号的序列来纠正您的错误,该问号不会终止pathname

这些属性非常适合将 URL 分解为它们的组成部分以供您处理,但在这种情况下您可能不想写入它们。相反,写信给location.href. 这代表了整个 URL,但是写一个相对 URL 是完全可以的;这将相对于当前值计算出来,因此实际上根本不需要读取和拆分pathname

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

注意 URL 编码。如果用户名可以包含字母数字以外的字符,您可能需要它来阻止这些字符破坏参数。在将任意字符串放入 URL 之前,始终对任意字符串进行 URL 编码。

于 2010-09-04T19:22:03.980 回答
15

尝试设置location.href属性而不是window.location.pathname.

于 2010-09-04T16:18:15.033 回答
8

使用window.location.href被认为是设置URL 的最安全方法。我认为这应该可以解决编码问题。

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

如果这没有帮助,请显示示例 URL。

于 2010-09-04T16:19:15.483 回答