append to url and refresh page

后端 未结 11 2126
终归单人心
终归单人心 2020-12-07 14:07

I am looking to write a piece of javascript that will append a parameter to the current url and then refresh the page - how can I do this?

相关标签:
11条回答
  • 2020-12-07 14:43

    If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:

    const parser = new URL(url || window.location);
    parser.searchParams.set(key, value);
    window.location = parser.href;
    
    0 讨论(0)
  • 2020-12-07 14:44
    function gotoItem( item ){
        var url = window.location.href;
        var separator = (url.indexOf('?') > -1) ? "&" : "?";
        var qs = "item=" + encodeURIComponent(item);
        window.location.href = url + separator + qs;
    }
    

    More compat version

    function gotoItem( item ){
        var url = window.location.href;    
        url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
        window.location.href = url;
    }
    
    0 讨论(0)
  • 2020-12-07 14:46

    One small bug fix for @yeyo's thoughtful answer above.

    Change:

    var parameters = parser.search.split(/\?|&/);

    To:

    var parameters = parser.search.split(/\?|&/);

    0 讨论(0)
  • 2020-12-07 14:51
    location.href = location.href + "&parameter=" + value;
    
    0 讨论(0)
  • Also:

    window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
    

    Just one liner of Shlomi answer usable in bookmarklets

    0 讨论(0)
  • 2020-12-07 14:53

    This line of JS code takes the link without params (ie before '?') and then append params to it.

    window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
    

    The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).

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