简体   繁体   中英

How can I add a parameter to my url, without reload the page?

I have this url http://localhost:1234/pag1

I want to be like below when I click on the div:

 http://localhost:1234/pag1?fare=standar

and I have an onclick event function:

 <div id="" onclick="addUrl();"> </div>

And the js code:

<script type="text/javascript">
 function addUrl() {
    var url = window.location.href;
    window.location.hash = '?fare=standar';
};
    </script>

This give me this result:

http://localhost:1234/pag1#?fare=standar

And I don't Know how to remove the (#). I only need to add the parameter to the url, without refresh the page.

Suggest me! Thank's.

Use window.history.pushState( {} , '', '?fare=standar' );

This should update the url without refresh.

You can also do a bit of reseach on pushState as the implementation can differ.

window.location.hash always put "#" in url

you can use to push paramter in url by using this function

function setGetParameter(paramName, paramValue)
{
    var url = window.location.href;
    if (url.indexOf(paramName + "=") >= 0)
    {
        var prefix = url.substring(0, url.indexOf(paramName));
        var suffix = url.substring(url.indexOf(paramName));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix;
    }
    else
    {
    if (url.indexOf("?") < 0)
        url += "?" + paramName + "=" + paramValue;
    else
        url += "&" + paramName + "=" + paramValue;
    }
    window.location.href = url;
}

i hope this will helpful to you

Try this

HTML

<div onclick="addUrl()"> </div>

Javascript

  <script type="text/javascript">
    function addUrl() {
    var url = window.history.pushState( {} , '', '?fare=standar' );
  </script>

Quick Explanation : When user clicks on div, URL will update without refreshing the page.

Hope this will work for you, thank you :-).

Try this

var myURL = document.location;
document.location = myURL + "?a=parameter";

Or

location.hash = 'a=parameter'

Or without reloading the page

window.history.pushState("object or string", "Title", "new url");

Or without reloading the page

window.history.replaceState(null, null, "/another-new-url");

Why dont you use jQuery? I prepared sample like here in JsFiddle :

$("#clickableDiv").click(function(){
  var url = "http://localhost:1234/pag1";
  var parameter = "fare=standar";
  $("#AppendUrl").text(url+ "?" + parameter);  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM