How to add a parameter to the URL?

后端 未结 9 998
遇见更好的自我
遇见更好的自我 2020-11-30 06:37

My current URL is: http://something.com/mobiles.php?brand=samsung

Now when a user clicks on a minimum price filter (say 300), I want my URL to become

相关标签:
9条回答
  • 2020-11-30 07:29

    If you're having the user fill out a textfield with a minimum price, why not let the form submit as a GET-request with a blank action? IIRC, that should do just what you want, without any javascript.

    0 讨论(0)
  • 2020-11-30 07:39

    Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:

    <script>
        function addParam(v) {
            window.location.search += '&' + v;
        }
    </script>
    
    <a href="javascript:addParam('priceMin=300');">add priceMin=300</a>
    

    There is no need to check for ? as this is already the search part and you only need to add the param.

    If you don't want to even make use of a function you can write as so:

    <a href="javascript:location.search+='&priceMin=300';">add priceMin=300</a>
    

    Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.

    Edit:

    In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:

    • if the parameter already exists, it should be changed.
    • if the parameter already exists multiple times, only the changed copy should survive.
    • if the parameter already exists, but have no value, the value should be set.

    As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:

    <script>
        function setParam(name, value) {
            var l = window.location;
    
            /* build params */
            var params = {};        
            var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;        
            var s = l.search;
            for(var r = x.exec(s); r; r = x.exec(s))
            {
                r[1] = decodeURIComponent(r[1]);
                if (!r[2]) r[2] = '%%';
                params[r[1]] = r[2];
            }
    
            /* set param */
            params[name] = encodeURIComponent(value);
    
            /* build search */
            var search = [];
            for(var i in params)
            {
                var p = encodeURIComponent(i);
                var v = params[i];
                if (v != '%%') p += '=' + v;
                search.push(p);
            }
            search = search.join('&');
    
            /* execute search */
            l.search = search;
        }
    </script>
    
    <a href="javascript:setParam('priceMin', 300);">add priceMin=300</a>
    

    This at least is a bit more robust as it can deal with URLs like these:

    test.html?a?b&c&test=foo&priceMin=300
    

    Or even:

    test.html?a?b&c&test=foo&pri%63eMin=300
    

    Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.

    0 讨论(0)
  • 2020-11-30 07:40
    var applyMinPrice = function(minPrice) {
        var existingParams = (location.href.indexOf('?') !== -1),
            separator = existingParams ? '&' : '?',
            newParams = separator + 'priceMin=' + minPrice;
    
        location.href += newParams;
    }
    
    0 讨论(0)
提交回复
热议问题