js 获取url 传值 参数

方法一:正则法截取

function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);

if (r != null) return unescape(r[2]); return null;
}

取值:var param=getQueryString('yourParamname');

 

方法二:字符串截取

function GetRequest() {
var url = location.search; //获取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++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}

取值:

var Request = new Object();
Request = GetRequest();

var param=getQueryString['yourParamname'];

 

方法三:匿名函数+正则+解码+捕获异常

var getParam = function (name) {
var search = document.location.search;
var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
var matcher = pattern.exec(search);
var items = null;
if (null != matcher) {
try {
items = decodeURIComponent(decodeURIComponent(matcher[1]));
} catch (e) {
try {
items = decodeURIComponent(matcher[1]);
} catch (e) {
items = matcher[1];
}
}
}
return items;
};

posted @ 2012-07-31 16:09  呓语  阅读(705)  评论(0编辑  收藏  举报
welcome to this garden! --Chenly