js原生_获取url键值对

思路:

1.先对url进行处理,获取 ?后的字符串

 postid=10457794&actiontip=保存修改成功')

2. 字符串通过&标识,不同参数转为数组

["postid=10457794", "actiontip=保存修改成功"]

3.分别将 = 左右两边拆分为数组, 动态变为键值对

["postid", "10457794"]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style></style>
</head>
<body>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.js"></script>
<script>
function getParamsFromUrl(url) {
if (url.indexOf("?") != -1) {
var index = url.indexOf('?') + 1;
// 得到?后的字符串
var str = url.substr(index); // postid=10457794&actiontip=保存修改成功')
var paramsObj ={};
// 字符串通过&标识,转为数组
arrs = str.split("&"); // ["postid=10457794", "actiontip=保存修改成功"]
for(var i = 0; i < arrs.length; i ++) {
// 分别将 = 左右两边拆分为数组, 动态变为键值对
paramsObj[arrs[i].split("=")[0]] = arrs[i].split("=")[1]
// arrs[i].split("=") ["postid", "10457794"]
}
}
return paramsObj
}
getParamsFromUrl('https://www.baidu.com?postid=10457794&actiontip=保存修改成功')
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/renzm0318/p/10681555.html