设置JavaScript的window.location

48

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

4个回答

67

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
1
请注意,在大多数情况下,您应该使用 location.host 而不是 location.hostname。简而言之,这是因为您的代码在某些时候可能会在端口号不是80的服务器上运行。 - Camilo Martin
请注意,在(罕见的)情况下,如果源是一个iframe,则需要执行window.parent.location..... - Amol Pujari

17

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


只需要 window.location = ... 就可以了。 - vsync
3
将值分配给 window.location 会在 TypeScript 中引发错误。我猜将其分配给 window.location.href 是更好的选择。 - mvermand

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"

    });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接