用javascript我怎么能添加一个查询字符串参数的url,如果不存在或如果它存在,更新当前值?我使用jquery为我的客户端开发。


当前回答

下面是我的方法:location.params()函数(如下所示)可以用作getter或setter。例子:

假设URL是http://example.com/?foo=bar&baz#some-hash,

Location.params()将返回一个包含所有查询参数的对象:{foo: 'bar', baz: true}。 Location.params ('foo')将返回'bar'。 的位置。params({foo: undefined, hello: 'world', test: true})会将URL更改为http://example.com/?baz&hello=world&test#some-hash。

下面是params()函数,它可以被选择性地分配给窗口。位置的对象。

location.params = function(params) {
  var obj = {}, i, parts, len, key, value;

  if (typeof params === 'string') {
    value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[&#$]?'));
    return value ? value[1] : undefined;
  }

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

  for (i = 0, len = _params.length; i < len; i++) {
    parts = _params[i].split('=');
    if (! parts[0]) {continue;}
    obj[parts[0]] = parts[1] || true;
  }

  if (typeof params !== 'object') {return obj;}

  for (key in params) {
    value = params[key];
    if (typeof value === 'undefined') {
      delete obj[key];
    } else {
      obj[key] = value;
    }
  }

  parts = [];
  for (key in obj) {
    parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
  }

  location.search = parts.join('&');
};

其他回答

如果它没有设置或想要更新一个新值,您可以使用:

window.location.search = 'param=value'; // or param=new_value

这是用简单Javascript写的。

EDIT

你可能想尝试使用jquery查询对象插件

窗口.位置.搜索 = jQuery.query.set(“param”, 5);

我想要的是:

使用浏览器的本地URL API 可以添加、更新、获取或删除吗 期望在散列之后的查询字符串,例如对于单页应用程序

function queryParam(options = {}) { var defaults = { method: 'set', url: window.location.href, key: undefined, value: undefined, } for (var prop in defaults) { options[prop] = typeof options[prop] !== 'undefined' ? options[prop] : defaults[prop] } const existing = (options.url.lastIndexOf('?') > options.url.lastIndexOf('#')) ? options.url.substr(options.url.lastIndexOf('?') + 1) : '' const query = new URLSearchParams(existing) if (options.method === 'set') { query.set(options.key, options.value) return `${options.url.replace(`?${existing}`, '')}?${query.toString()}` } else if (options.method === 'get') { const val = query.get(options.key) let result = val === null ? val : val.toString() return result } else if (options.method === 'delete') { query.delete(options.key) let result = `${options.url.replace(`?${existing}`, '')}?${query.toString()}` const lastChar = result.charAt(result.length - 1) if (lastChar === '?') { result = `${options.url.replace(`?${existing}`, '')}` } return result } } // Usage: let url = 'https://example.com/sandbox/#page/' url = queryParam({ url, method: 'set', key: 'my-first-param', value: 'me' }) console.log(url) url = queryParam({ url, method: 'set', key: 'my-second-param', value: 'you' }) console.log(url) url = queryParam({ url, method: 'set', key: 'my-second-param', value: 'whomever' }) console.log(url) url = queryParam({ url, method: 'delete', key: 'my-first-param' }) console.log(url) const mySecondParam = queryParam({ url, method: 'get', key: 'my-second-param', }) console.log(mySecondParam) url = queryParam({ url, method: 'delete', key: 'my-second-param' }) console.log(url)

我从这里得出的结论(与“使用严格”相容;并不真正使用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);
}

使用示例:

// 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()));
});

是的,我有一个问题,我的查询字符串会溢出和复制,但这是由于我自己的懒惰。所以我玩了一点,并研究了一些js jquery(实际上是sizzle)和c#魔法。

所以我才意识到,在服务器已经完成了传递的值,这些值不再重要,没有重用,如果客户端想做同样的事情,显然它将总是一个新的请求,即使它是相同的参数被传递。这些都是客户端,所以一些缓存/cookie等在这方面可能很酷。

JS:

$(document).ready(function () {
            $('#ser').click(function () {
                SerializeIT();
            });
            function SerializeIT() {
                var baseUrl = "";
                baseUrl = getBaseUrlFromBrowserUrl(window.location.toString());
                var myQueryString = "";
                funkyMethodChangingStuff(); //whatever else before serializing and creating the querystring
                myQueryString = $('#fr2').serialize();
                window.location.replace(baseUrl + "?" + myQueryString);
            }
            function getBaseUrlFromBrowserUrl(szurl) {
                return szurl.split("?")[0];
            } 
            function funkyMethodChangingStuff(){
               //do stuff to whatever is in fr2
            }
        });

HTML:

<div id="fr2">
   <input type="text" name="qURL" value="http://somewhere.com" />
   <input type="text" name="qSPart" value="someSearchPattern" />
</div>
<button id="ser">Serialize! and go play with the server.</button>

C#:

    using System.Web;
    using System.Text;
    using System.Collections.Specialized;

    public partial class SomeCoolWebApp : System.Web.UI.Page
    {
        string weburl = string.Empty;
        string partName = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string loadurl = HttpContext.Current.Request.RawUrl;
            string querySZ = null;
            int isQuery = loadurl.IndexOf('?');
            if (isQuery == -1) { 
                //If There Was no Query
            }
            else if (isQuery >= 1) {
                querySZ = (isQuery < loadurl.Length - 1) ? loadurl.Substring(isQuery + 1) : string.Empty;
                string[] getSingleQuery = querySZ.Split('?');
                querySZ = getSingleQuery[0];

                NameValueCollection qs = null;
                qs = HttpUtility.ParseQueryString(querySZ);

                weburl = qs["qURL"];
                partName = qs["qSPart"];
                //call some great method thisPageRocks(weburl,partName); or whatever.
          }
      }
  }

好的,批评是受欢迎的(这是一个夜间调制,所以请随时注意调整)。如果这有帮助的话,竖起大拇指,快乐编码。

没有重复,每个请求都是唯一的,因为你修改了它,并且由于它的结构,很容易从dom内动态添加更多的查询。

这样做的目的是:

function updateQueryString(url, key, value) {
    var arr =  url.split("#");
    var url = arr[0];
    var fragmentId = arr[1];
    var updatedQS = "";
    if (url.indexOf("?") == -1) {
        updatedQS = encodeURIComponent(key) + "=" + encodeURIComponent(value);
    }
    else {
        updatedQS = addOrModifyQS(url.substring(url.indexOf("?") + 1), key, value); 
    }
    url = url.substring(0, url.indexOf("?")) + "?" + updatedQS;
    if (typeof fragmentId !== 'undefined') {
        url = url + "#" + fragmentId;
    }
    return url;
}

function addOrModifyQS(queryStrings, key, value) {
    var oldQueryStrings = queryStrings.split("&");
    var newQueryStrings = new Array();
    var isNewKey = true;
    for (var i in oldQueryStrings) {
        var currItem = oldQueryStrings[i];
        var searchKey = key + "=";
        if (currItem.indexOf(searchKey) != -1) {
            currItem = encodeURIComponent(key) + "=" + encodeURIComponent(value);
            isNewKey = false;
        }
        newQueryStrings.push(currItem);
    }
    if (isNewKey) {
        newQueryStrings.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
    }
    return newQueryStrings.join("&");
}