设置 JavaScript window.location

问题描述 投票:0回答:4

我当前正在设置 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。

javascript window.location
4个回答
67
投票

pathname
以及
location
的许多其他属性和链接仅反映 URL 的 part

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 编码。


17
投票

尝试设置

location.href
属性而不是
window.location.pathname


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。


0
投票

ב”ה

在您的情况下,您可以设置

location.search
属性,而无需知道/重置/解码整个 URL。

location.search = 'u=' + selected_user

或者如果你有很多参数和很多不同类型的字符

location.search = (
    new URLSearchParams({
       u: selected_user,
       otherThing: "hi this %#%##^ is a "+
          "Very •}€○♡●¡● complex string"

    })
)+"";

© www.soinside.com 2019 - 2024. All rights reserved.