总结:客户端与服务器端使用正则增加URL参数的方法
先说服务器端的:
C#版本
#region URL参数操作 /// <summary> /// URL参数操作 /// </summary> public class UrlPageHelper { /// <summary> /// 以正则表达式方式增加URL参数 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public static string AddUrlParm(string key, string value) { string Url = HttpContext.Current.Request.RawUrl; Url = Regex.Replace(Url + "&", @"(.*)(\?|&)" + key + "=[^&]+?(&)(.*)", "$1$2$4", RegexOptions.IgnoreCase); Url = Url.Remove(Url.Length - 1); if (Url.Contains('?')) { Url = string.Format("{0}&{1}={2}", Url, key, value); } else { Url = string.Format("{0}?{1}={2}", Url, key, value); } return Url; } } #endregion
PHP版本
/** * 添加URL参数 * @param string $url 原URL * @param string $key 键 * @param string $value 值 * @return string 新URL */ private function add_querystring_var($key, $value) { $url = $this->url; $url=preg_replace('/(.*)(\?|&)'.$key.'=[^&]+?(&)(.*)/i','$1$2$4',$url.'&'); $url=substr($url,0,-1); if(strpos($url,'?') === false){ return ($url.'?'.$key.'='.$value); } else { return ($url.'&'.$key.'='.$value); } }
然后是客户端的
(function ($) { $.extend({ Request: function (m) { var sValue = location.search.match(new RegExp("[\?\&]" + m + "=([^\&]*)(\&?)", "i")); return sValue ? sValue[1] : sValue; }, UrlUpdateParams: function (url, name, value) { var r = url; if (r != null && r != 'undefined' && r != "") { value = encodeURIComponent(value); var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)"); var tmp = name + "=" + value; if (url.match(reg) != null) { r = url.replace(eval(reg), tmp); } else { if (url.match("[\?]")) { r = url + "&" + tmp; } else { r = url + "?" + tmp; } } } return r; } }); })(jQuery);
客户端使用方法:
$.UrlUpdateParams(window.location.href, "order", "111")