开发者

Get anchor from URI

I'm writing a JSP/Servlet and I'm trying to get the the anchor part of the URI e.g:

blabla.rdf#mark
开发者_高级运维

How do I get my mark from my request? Obviously request.getParameter() doesn't work?

Any help would be welcome.


This isn't possible as clients don't send the "anchor part" to the server

As an example, here's the exact request that Chrome generated after submitting http://example.com/#foobar (recorded using Wireshark):

GET / HTTP/1.1
Host: example.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/532.3 (KHTML, like Gecko) Chrome/4.0.223.11 Safari/532.3
Cache-Control: max-age=0
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Encoding: gzip,deflate
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
If-None-Match: "b300b4-1b6-4059a80bfd280"
If-Modified-Since: Tue, 15 Nov 2005 13:24:10 GMT

See, no #foobar. So there's no way a server application can read it.

You could do some JavaScript magic to store the anchor in a cookie or in a hidden input field or whatever voodoo you're into. But it won't ever work for requests that don't originate from your own sites. It's simpler to make whatever you need on the server part of the query string and use the anchor only for JavaScript-only tasks - or use it to navigate inside a simple HTML document - but that's so 90s ;).

Here's the important part from the mentioned RFC 1808:

Note that the fragment identifier (and the "#" that precedes it) is not considered part of the URL. However, since it is commonly used within the same string context as a URL, a parser must be able to recognize the fragment when it is present and set it aside as part of the parsing process.


I guess you want to make a bookmarkable Ajax web-application and you want to replace certain fragments of the DOM without reloading the full page. (Otherwise you could use query parameters.) As sfussenegger mentions, browser doesn't transmit 'anchor' to the server. The solution is on the client-side.

Javascript window.location.hash gives the anchor information. You can append an event handler to the window.onload event which grabs window.location.hash and transmits it to the server in an Ajax XHttpRequest. You catch the response and build it into the DOM.

Unfortunately, it's two client-server roundtrips.

More on this at ajaxpatterns.


This solution would only work after a submit button has been pushed, but: you could use javascript to place a hidden value on your form that is set to the value of document.location. That would tell you exactly what the browser is seeing as your address.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜