傳參文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jq路由傳參</title>
<script src="../assets/js/jquery_2.1.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../assets/js/jqExpand.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
$("button").click(function() {
var testObj = {
name: "xxx",
age: 22,
country: "中國"
}
// console.log(urlEncode(testObj))
window.location.href = "jq接收路由參數(shù).html?" + urlEncode(testObj)
})
})
</script>
</head>
<body>
<button type="button">點(diǎn)我攜帶參數(shù)跳轉(zhuǎn)到子頁面</button>
</body>
</html>
接收參數(shù):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jq接收路由參數(shù)</title>
<script src="../assets/js/jquery_2.1.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../assets/js/jqExpand.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
var obj = GetRequest();
// console.log(obj)
var show = ""
Object.keys(obj).map((key)=>{
console.log(obj[key])
show += "<p>" + obj[key] + "</p>"
})
document.write(show)
})
</script>
</head>
<body>
</body>
</html>
自己封裝的擴(kuò)展文件(jqExpand):
/**
* paramObj 將要轉(zhuǎn)為URL參數(shù)字符串的對象
* key URL參數(shù)字符串的前綴
* encode true/false 是否進(jìn)行URL編碼,默認(rèn)為true
* js實(shí)現(xiàn)
* return URL參數(shù)字符串
*/
var urlEncode = function(paramObj, key, encode) {
if (paramObj == null) return '';
var paramStr = '';
var t = typeof(paramObj);
if (t == 'string' || t == 'number' || t == 'boolean') {
paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(paramObj) : paramObj);
} else {
for (var i in paramObj) {
var k = key == null ? i : key + (paramObj instanceof Array ? '[' + i + ']' : '.' + i);
paramStr += urlEncode(paramObj[i], k, encode);
}
// console.log(paramStr)
paramStr = paramStr.replace(/^&/g, "")
}
return paramStr;
};
//根據(jù)參數(shù)名稱獲取url參數(shù)
function getUrlParamValue(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURIComponent(r[2]);
return null;
}
//獲取url參數(shù)封裝成對象
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]] = decodeURIComponent((strs[i].split("=")[1]));
}
}
return theRequest;
}