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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM