设置JavaScript window.location [英] Setting JavaScript window.location
问题描述
我目前正在设置window.location.pathname属性以将用户重定向到相对URL。新URL包含参数,因此JavaScript行如下所示:
I'm currently setting the window.location.pathname property to redirect the user to a relative URL. The new URL has parameters, so the line of JavaScript looks like this:
window.location.pathname = window.location.pathname.substring( 0, window.location.pathname.lastIndexOf( '/' ) + 1 ) + 'myPage.xhtml?u=' + selected_user.Username;
这在Firefox中很成功,但Chrome会使用'%3F'对问号进行编码,随后请求失败。
This is successful in Firefox, however Chrome encodes the question mark with '%3F' and the request subsequently fails.
我不确定我是否正确使用window.location。我是否需要使用window.location的属性,例如pathname或href?我发现,只要我设置了一个属性,就会重新加载该位置,因此,例如,不能单独设置搜索和路径名属性。可以直接设置window.location吗?我只需要设置一个带参数的相对URL。
I'm not sure if I'm using window.location properly. Do I need to use properties of window.location such as pathname or href? I've found that as soon as I set one property the location is reloaded, so for example, the search and pathname properties can't be set separately. Can window.location be set directly? I only need to set a relative URL with a parameter.
推荐答案
pathname
以及 location
的许多其他属性和链接仅反映网址的部分:
pathname
and many other properties of location
and links reflect only part of the URL:
http: //www.example.com/path/to/example.html?param1=2¶m3=4#fragment
^protocol^hostname ^pathname ^search ^hash
如你所见,?...
部分网址不属于路径名
;将包含?
的值写入 location.pathname
是没有意义的,因为URL的该部分不能包含问号。 Chrome通过将字符编码为序列来纠正错误,该序列意味着文字问号,该问号不会终止路径名
。
As you can see, the ?...
part of the URL is not part of the pathname
; it makes no sense to write a value containing ?
to location.pathname
, as that part of a URL cannot contain a question mark. Chrome is correcting your mistake by encoding the character to a sequence that means a literal question mark, which doesn't terminate pathname
.
这些属性非常适合将URL分解为其组成部分以供您处理,但在这种情况下您可能不想写入它们。而是写入 location.href
。这表示整个URL,但写一个相对URL是完全正常的;这将相对于当前值计算出来,因此实际上根本不需要读取和拆分路径名
:
These properties are great for breaking a URL into their constituent parts for you to process, but you probably don't want to write to them in this case. Instead, write to location.href
. This represents the whole URL, but it's perfectly fine to write a relative URL to it; this will be worked out relative to the current value, so there is in fact no need to read and split the pathname
at all:
location.href= 'myPage.xhtml?u='+encodeURIComponent(selected_user.Username);
请注意URL编码。如果用户名可以包含字母数字以外的字符,您可能需要这个来阻止那些破坏参数的字符。在将任意字符串放入URL的一部分之前,始终对其进行URL编码。
Note the URL-encoding. If a username can contain characters other than alphanumerics you will probably need this to stop those characters breaking the parameter. Always URL-encode arbitrary strings before putting them into part of a URL.
这篇关于设置JavaScript window.location的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!