基于JavaScript獲取url參數(shù)2種方法
這次是使用JavaScript來獲取url(request)中的參數(shù)
在日常頁(yè)面編寫的過程中為了方便操作在<script>中通過使用window.location.href='http://m.lshqa.cn/bcjs/要跳轉(zhuǎn)的頁(yè)面?參數(shù)1=' rel='external nofollow' +值1+'&參數(shù)2='+值2 來進(jìn)行頁(yè)面跳轉(zhuǎn)并傳值。
那么在跳轉(zhuǎn)過去的頁(yè)面怎樣在<script>中獲取到傳過來的參數(shù)呢?
下面是小編的一個(gè)案例:
//參數(shù)傳出頁(yè)面
window.location.href = 'http://m.lshqa.cn/bcjs/Frameset.aspx?name=' + username + '&tbpwd='+tbpwd;//這里是我要將username和tbpwd作為參數(shù)傳到Frameset.aspx這個(gè)頁(yè)面上
一、字符串分割分析法
//參數(shù)接收頁(yè)面(Frameset.aspx) <script type='text/javascript' language='javascript'> $(function () { var url = location.search; ////獲取接收到的url中含'?'符后的字串 var request = new Object(); //實(shí)例化一個(gè)對(duì)象 if (url.indexOf('?') != -1) { //判斷“?”后面是否有值var str = url.substr(1) //去掉括?號(hào)strs = str.split('&');for (var i = 0; i < strs.length; i++){ request[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);//將參數(shù)和對(duì)應(yīng)的值使用split函數(shù)切割出來} } //以此獲取url串中所帶的同名參數(shù) alert(request['name']); alert(request['tbpwd']); }) </script>
二、正則分析法
<script type='text/javascript' language='javascript'>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;}alert(GetQueryString('參數(shù)名1'));alert(GetQueryString('參數(shù)名2'));</script>
以上兩種方法都是可以實(shí)現(xiàn)js通過window.location.href進(jìn)行頁(yè)面跳轉(zhuǎn)及傳參后在跳轉(zhuǎn)后的頁(yè)面接收到參數(shù)!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
