如何在URL参数中提交哈希键? [英] How can I submit a hash key in an URL parameter?
问题描述
我有一个以Freemarker作为视图组件的Spring-MVC应用程序.
在我的模板中,会生成几个指向我的应用程序的链接,这些链接包括包含哈希键(#
)的URL参数.
示例:
参数:Q#106368 11
由Freemarker生成的具有已编码参数的URL:testurl.html?key=Q%23106368%2011
我使用JavaScript重定向到该URL(原因:我使用JS来同时管理2帧的加载).
重定向方法很简单:
function redir(url) {
window.location.href = url;
}
Freemarker生成的JS调用看起来像
<a href="javascript:redir('http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011');">test</a>
我的问题是浏览器/Javascript将URL编码参数转换回去,认为存在#
并在此切断.
当我直接使用window.location.href='http://...'
时,它可以工作.仅当使用method参数时,URL似乎才能神奇地解码,然后重定向失败,因为URL在#
处被切断.
有一种简便的方法可以正确地传输参数吗?
我知道我可以替换#
,例如在模板中使用$$$hash$$$
,然后再次在服务器端进行替换.但是有很多地方我不得不改变...
正如Marc B所说,有必要再次对URL进行编码.该方法为encodeURI()
.但是,此方法不对#
符号进行编码.对于我的特定用例,我必须在编码后用%23
替换#
符号.
重定向JS方法最终看起来像:
function redir(url) {
url = encodeURI(url);
url = url.replace(/#/g, '%23');
window.location.href = url;
}
比较escape(),encodeURI()和encodeURIComponent() >
I have a Spring-MVC application with Freemarker as the view component.
In my templates, several links are generated which point back to my application and which include URL parameters containing a hash key (#
).
Example:
parameter: Q#106368 11
URL generated by Freemarker with encoded param: testurl.html?key=Q%23106368%2011
I use JavaScript to redirect to this URL (reason: I use JS to manage loading of 2 frames at the same time).
The redirect method is simple:
function redir(url) {
window.location.href = url;
}
The JS call generated by Freemarker looks like
<a href="javascript:redir('http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011');">test</a>
My problem is that the browser / Javascript converts back the URL encoded parameter, thinks there is a #
and cuts off there.
When I use window.location.href='http://...'
directly it works. Only when using the method parameter it seems to be magically URL decoded and then the redirect fails because the URL gets cut off at the #
.
Is there an easy way to transmit the parameter correctly?
I am aware that I could replace the #
, e.g. with $$$hash$$$
, in the template and do the replacement on the server side again. But there are so many places I would have to change...
As Marc B commented, it is necessary to URL encode again. The method would be encodeURI()
. However, this method does not encode the #
sign. For my specific use case, I have to replace the #
sign with %23
after the encoding.
The redirect JS method finally looks like:
function redir(url) {
url = encodeURI(url);
url = url.replace(/#/g, '%23');
window.location.href = url;
}
Comparing escape(), encodeURI(), and encodeURIComponent()
这篇关于如何在URL参数中提交哈希键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!