Append parameter in url without reloading page

我的梦境 提交于 2019-12-31 03:54:35

问题


I am using following code to append param to url. This is working fine but when parameter is appended in url, page is getting reloaded. I want to use this functionality without reloading the page .

function insertParam(key, value)
{
    key = escape(key); value = escape(value);

    var kvp = document.location.search.substr(1).split('&');


    var i=kvp.length; var x; while(i--) 
    {
        x = kvp[i].split('=');

        if (x[0]==key)
        {
                x[1] = value;
                kvp[i] = x.join('=');
                    alert('sdfadsf');
                break;
        }
    }

    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    document.location.search = kvp.join('&'); 
    //alert(document.location.href);

}

I want to add multiple params to url without reloading the page like:

  • txt1
  • txt2
  • txt3
  • link1
  • link2
  • link3

i want url : "..../search.php"

after click on txt2 i want url : "..../search.php#t_2"

after click on link2 i want url : "..../search.php#t_1&l_2"


回答1:


You can only do this using history.pushState(state, title, url) which is an HTML5 feature.




回答2:


There is a new feature that aims to replace the use of location.hash with a better solution: pushState.

 window.history.pushState(data, "Title", "/new-url");

More information: http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate



来源:https://stackoverflow.com/questions/10445229/append-parameter-in-url-without-reloading-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!