通过javascript获取get请求的参数

整个类的代码如下:

/**
* 获取get请求中的参数
*
* @author MaLong
* @param loc
* (可选String or Object) String 类型须为URL, Object则为Location的对象
* 默认为window.location
*/
var Request = function(loc) {
var paramsStr;
var hashSearchString;
if (!loc || typeof loc == "object") {
loc = loc || window.location;
if (/#.+\?/.test(paramsStr)) {
paramsStr = loc.hash;
} else
paramsStr = loc.search;
} else if (typeof loc == "string") {
if (/.*\?.+[#.+]?/.test(loc))
paramsStr = loc.replace(/.*\?/, "");
else
paramsStr = loc.replace(/.*#/, "#");
}
if (!/#.+\?/.test(paramsStr)) {
this.pageSelector = paramsStr.replace(/^\?.*#$/, "#");
hashSearchString = paramsStr.replace(/\?|(#.+)/, "");
} else {
this.pageSelector = paramsStr.replace(/\?.*$/, "");
hashSearchString = paramsStr.replace(/#.+\?/, "");
}
var params = hashSearchString.split("&");
var reg = /^(\w+)=(.*)$/;
this.paramsMap = {};
for ( var i = 0, length = params.length; i < length; i++) {
var _p = reg.exec(params[i]);
if (_p)
this.paramsMap[_p[1]] = _p[2];
}
}
Request.prototype = {
/**
* 根据参数名获取参数值
*
* @param name
* @return 参数值
*/
getParam : function(name) {
return this.paramsMap[name];
},
/**
* 设置参数名和参数值
*
* @param name
* 参数名
* @param value
* 参数值
*/
setParam : function(name, value) {
this.paramsMap[name] = value;
},
/**
* 获取所有参数
*
* @returns 封装所有参数名和参数值的json
*/
getParams : function() {
return this.paramsMap;
},
/**
*
*/
paramSize : function() {
},
/**
*
*/
getHashParam : function() {
},
/**
* pageSelector 为通过hash值改变页面而预留,例:xxx.com#pageSelector
*/
getPageSelector : function() {
return this.pageSelector;
}
}


调用:


if(!/.*\?.+/.test(dataUrl))
dataUrl=window.location;
//dataUrl 可选
var request = new Request(dataUrl);
var userName=request.getParam("userName");

你可能感兴趣的:(网络编程)