使用jQuery更新现有的URL查询字符串值 [英] Updating existing URL querystring values with jQuery

查看:114
本文介绍了使用jQuery更新现有的URL查询字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个网址,例如:

Let's say I have a url such as:

http://www.example.com/hello.png?w=100&h=100&bg=white

我想要做的是更新w和h查询字符串的值,但保持bg查询字符串不变,例如:

What I'd like to do is update the values of the w and h querystring, but leave the bg querystring intact, for example:

http://www.example.com/hello.png?w=200&h=200&bg=white

那么最快的是什么读取查询字符串值的最有效方法(它们可以是任何一组查询字符串值,而不仅仅是w,h和bg),更新一些值或不更新值,并使用新的查询字符串返回完整的URL?

So what's the fastest most efficient way to read the querystring values (and they could be any set of querystring values, not just w, h, and bg), update a few or none of the values, and return the full url with the new querystring?

所以:


  1. 获取每个查询字符串键的值

  2. 更新任意数量的密钥

  3. 使用新值重建网址

  4. 保留所有其他值不是已更新

  5. 它没有标准的已知密钥集,可能会更改每个网址

  1. Get the values of each querystring key
  2. Update any number of the keys
  3. Rebuild the url with the new values
  4. Keep all of the other values which weren't updated
  5. It will not have a standard set of known keys, it could change per URL


推荐答案

获取查询字符串值方式并使用 $ .param 重建查询字符串

Get query string values this way and use $.param to rebuild query string

更新:

这是一个例子,同时检查小提琴

This is an example, also check fiddle:

  function getQueryVariable(url, variable) {
  	 var query = url.substring(1);
     var vars = query.split('&');
     for (var i=0; i<vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
     }

     return false;
  }

  var url = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
       
  var w = getQueryVariable(url, 'w');
  var h = getQueryVariable(url, 'h');
  var bg = getQueryVariable(url, 'bg');

  // http://www.example.com/hello.png?w=200&h=200&bg=white
  var params = { 'w':200, 'h':200, 'bg':bg };
  var new_url = 'http://www.example.com/hello.png?' + jQuery.param(params);

您可以将功能更改为使用当前网址:

You can change the function to use current url:

  function getQueryVariable(variable) {
  	 var query = window.location.search.substring(1);
     var vars = query.split('&');
     for (var i=0; i<vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
     }

     return false;
  }

这篇关于使用jQuery更新现有的URL查询字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆