jQuery/Javascript - reload current page with an appended querystring?

后端 未结 6 466
小鲜肉
小鲜肉 2021-02-03 18:40

I\'ve got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.

How would I go about doing th

6条回答
  •  清酒与你
    2021-02-03 18:51

    If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.

    $("#sortby").change(function () {
    
        var queryString = getQueryStrings();
        // Add new params to the querystring dictionary
        queryString["sortby"] = $("#sortby").val();
    
        window.location.href =
            window.location.protocol + "//" +
            window.location.host +
            window.location.pathname +
            createQueryString(queryString);
    });
    
    
    // http://stackoverflow.com/questions/2907482
    // Gets Querystring from window.location and converts all keys to lowercase
    function getQueryStrings() {
        var assoc = {};
        var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
        var queryString = location.search.substring(1);
        var keyValues = queryString.split('&');
    
        for (var i in keyValues) {
            var key = keyValues[i].split('=');
            if (key.length > 1) {
                assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
            }
        }
    
        return assoc;
    }
    
    function createQueryString(queryDict) {
        var queryStringBits = [];
        for (var key in queryDict) {
            if (queryDict.hasOwnProperty(key)) {
                queryStringBits.push(key + "=" + queryDict[key]);
            }
        }
        return queryStringBits.length > 0
            ? "?" + queryStringBits.join("&")
            : "";
    }
    

提交回复
热议问题