How to add url parameter to the current url?

后端 未结 7 400
小鲜肉
小鲜肉 2020-12-08 06:49

Currently I\'m at

http://example.com/topic.php?id=14 

and I want to make a link to

http://example.com/topic.php?id=14&         


        
相关标签:
7条回答
  • 2020-12-08 06:52

    There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

    You have to:

    topic.php?id=14&like=like
    
    0 讨论(0)
  • 2020-12-08 06:56

    I know I'm late to the game, but you can just do ?id=14&like=like by using http build query as follows:

    http_build_query(array_merge($_GET, array("like"=>"like")))
    

    Whatever GET parameters you had will still be there and if like was a parameter before it will be overwritten, otherwise it will be included at the end.

    0 讨论(0)
  • 2020-12-08 07:05

    It is not elegant but possible to do it as one-liner <a> element

    <a href onclick="event.preventDefault(); location+='&like=like'">Like</a>

    0 讨论(0)
  • 2020-12-08 07:09

    If you wish to use "like" as a parameter your link needs to be:

    <a href="/topic.php?like=like">Like</a>
    

    More likely though is that you want:

    <a href="/topic.php?id=14&like=like">Like</a>
    
    0 讨论(0)
  • 2020-12-08 07:13
    function currentUrl() {
        $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
        $host     = $_SERVER['HTTP_HOST'];
        $script   = $_SERVER['SCRIPT_NAME'];
        $params   = $_SERVER['QUERY_STRING'];
    
        return $protocol . '://' . $host . $script . '?' . $params;
    }
    

    Then add your value with something like;

    echo currentUrl().'&value=myVal';
    
    0 讨论(0)
  • 2020-12-08 07:14

    In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:

    <script>
    function addUrlParameter(name, value) {
      var searchParams = new URLSearchParams(window.location.search)
      searchParams.set(name, value)
      window.location.search = searchParams.toString()
    }
    </script>
    
    <body>
    ...
      <a onclick="addUrlParameter('like', 'like')">Like this page</a>
    ...
    </body>
    
    0 讨论(0)
提交回复
热议问题