开发者

How can I submit a hash key in an URL parameter?

开发者 https://www.devze.com 2023-03-18 19:44 出处:网络
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 ha

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


encodeURIComponent/decodeURIComponent is more thorough than just encodeURI, it will decode/encode '#' and event '/'


What browser are you using? I'm trying FireFox 5 and it doesn't convert %23 back into # in my testing. When you mouse over the link or copy the link location, what does that have? Are you sure whatever is outputting the link isn't doing the conversion?

Update

This isn't ideal, but it seems like it solves the problem:

<a onclick="url = 'http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011';" href="javascript:redir(url);">test</a>

It seems like the href attribute is decoded. When I mouse over it I seen the # instead of the %23.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号