Proper URL forming with Query String and Anchor Hashtag

前端 未结 5 1511
粉色の甜心
粉色の甜心 2020-12-04 11:27

When both a query string and anchor tag (hash tag) are visible in a URL, what is the proper order for them to appear?

http://www.whatever.com?var=val#anchor

相关标签:
5条回答
  • 2020-12-04 12:11

    If intention of using # is to denote page fragment then - yes ? then #.

    If # is coming before ? and it is not to denote page fragment (this can happen when # is part of authority (username and password)) it has to be encoded or you are in trouble. Same applies to any other special characters (:,@,...) that could give different meaning to url.

    0 讨论(0)
  • 2020-12-04 12:13

    Note that when the URL has both anchor tags (#) and query strings (?), the browser may ignore the query string and navigate to the anchor tag without reloading the page.

    It may be necessary to submit the page using a

        <form action='webpage.php?q=string#tag' method='GET or POST'>
        <input type='text' id='q' name='q' value='string'>
        <input type='submit' value='submit'>
        </form> 
    

    rather than just a URL link

        <a href='webpage.php?q=string#tag'>.
    
    0 讨论(0)
  • 2020-12-04 12:25

    You may place this javascript in the common part of your site to force redirecting all incorrect requests to the analog with proper order:

    <script>
        var p=location.hash.indexOf("?");
        if(p>=0){
            var goodLoc = location.href.replace(location.hash,"");
            location.replace(goodLoc + window.location.hash.substring(p) + window.location.hash.substring(0,p));
        }
    </script>
    
    0 讨论(0)
  • 2020-12-04 12:27

    ? should come before the # as noted in RFC 3986:

    relative-ref = relative-part [ "?" query ] [ "#" fragment ]
    

    Taken from an answer over at superuser (https://superuser.com/questions/498617/does-an-anchor-tag-come-before-the-query-string-or-after):

    0 讨论(0)
  • 2020-12-04 12:32
    ?var=var#hash
    

    everything after # is client side.

    Also, look into url rewriting to get rid of ugly ?var=var

    0 讨论(0)
提交回复
热议问题