获取url中参数的几种方法

举例地址:http://www.gj-china.net/frontend/companylist.html?type=1&code=2

方法一

var LocString = String(window.document.location.href);
function getQueryStr(str) {
var rs = new RegExp("(^|)" + str + "=([^/&]*)(/&|$)", "gi").exec(LocString);
var tmp;
if (tmp = rs) {
return tmp[2];
}
return "";
}
//调用
var type=getQueryStr('type');
 

方法二

function GetRequest() {
var url = decodeURI(location.search); //获取url中"?"符后的字串
//alert(url);
var theRequest = new Object();
if (url.indexOf("?") !== -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
//alert(strs);
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
}
//调用
var Request = new Object();
Request = GetRequest();
var type = Request["type"];
 

方法三

UrlParm = function() { // url参数
var data, index;
(function init() {
data = [];
index = {};
var u = window.location.search.substr(1);
if (u != '') {
var parms = decodeURIComponent(u).split('&');
for (var i = 0, len = parms.length; i < len; i++) {
if (parms[i] != '') {
var p = parms[i].split("=");
if (p.length == 1 || (p.length == 2 && p[1] == '')) {// p | p=
data.push(['']);
index[p[0]] = data.length - 1;
} else if (typeof(p[0]) == 'undefined' || p[0] == '') { // =c | =
data[0] = [p[1]];
} else if (typeof(index[p[0]]) == 'undefined') { // c=aaa
data.push([p[1]]);
index[p[0]] = data.length - 1;
} else {// c=aaa
data[index[p[0]]].push(p[1]);
}
}
}
}
})();
return {
// 获得参数,类似request.getParameter()
parm : function(o) { // o: 参数名或者参数次序
try {
return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);
} catch (e) {
}
},
//获得参数组, 类似request.getParameterValues()
parmValues : function(o) { // o: 参数名或者参数次序
try {
return (typeof(o) == 'number' ? data[o] : data[index[o]]);
} catch (e) {}
},
//是否含有parmName参数
hasParm : function(parmName) {
return typeof(parmName) == 'string' ? typeof(index[parmName]) != 'undefined' : false;
},
// 获得参数Map ,类似request.getParameterMap()
parmMap : function() {
var map = {};
try {
for (var p in index) { map[p] = data[index[p]]; }
} catch (e) {}
return map;
}
}
}();
//调用
var name=UrlParm.parm("name");

你可能感兴趣的:(获取url中参数的几种方法)