Setting JavaScript window.location

社会主义新天地 提交于 2019-11-28 04:29:44

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&param3=4#fragment
^protocol^hostname      ^pathname            ^search           ^hash

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.

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);

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.

Try setting the location.href property instead of window.location.pathname.

Using window.location.href is considered the safest way to set a URL. I think this should fix the encoding problem.

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

If that doesn't help, please show an example URL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!