How can I add or update a query string parameter?

后端 未结 27 2846
别那么骄傲
别那么骄傲 2020-11-22 02:35

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development

27条回答
  •  感情败类
    2020-11-22 03:15

    My take from here (compatible with "use strict"; does not really use jQuery):

    function decodeURIParams(query) {
      if (query == null)
        query = window.location.search;
      if (query[0] == '?')
        query = query.substring(1);
    
      var params = query.split('&');
      var result = {};
      for (var i = 0; i < params.length; i++) {
        var param = params[i];
        var pos = param.indexOf('=');
        if (pos >= 0) {
            var key = decodeURIComponent(param.substring(0, pos));
            var val = decodeURIComponent(param.substring(pos + 1));
            result[key] = val;
        } else {
            var key = decodeURIComponent(param);
            result[key] = true;
        }
      }
      return result;
    }
    
    function encodeURIParams(params, addQuestionMark) {
      var pairs = [];
      for (var key in params) if (params.hasOwnProperty(key)) {
        var value = params[key];
        if (value != null) /* matches null and undefined */ {
          pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
        }
      }
      if (pairs.length == 0)
        return '';
      return (addQuestionMark ? '?' : '') + pairs.join('&');
    }
    
    //// alternative to $.extend if not using jQuery:
    // function mergeObjects(destination, source) {
    //   for (var key in source) if (source.hasOwnProperty(key)) {
    //     destination[key] = source[key];
    //   }
    //   return destination;
    // }
    
    function navigateWithURIParams(newParams) {
      window.location.search = encodeURIParams($.extend(decodeURIParams(), newParams), true);
    }
    

    Example usage:

    // add/update parameters
    navigateWithURIParams({ foo: 'bar', boz: 42 });
    
    // remove parameter
    navigateWithURIParams({ foo: null });
    
    // submit the given form by adding/replacing URI parameters (with jQuery)
    $('.filter-form').submit(function(e) {
      e.preventDefault();
      navigateWithURIParams(decodeURIParams($(this).serialize()));
    });
    

提交回复
热议问题