基于JavaScript獲取url參數(shù)2種方法
這次是使用JavaScript來獲取url(request)中的參數(shù)
在日常頁面編寫的過程中為了方便操作在<script>中通過使用window.location.href='http://m.4tl426be.cn/bcjs/要跳轉(zhuǎn)的頁面?參數(shù)1=' rel='external nofollow' +值1+'&參數(shù)2='+值2 來進(jìn)行頁面跳轉(zhuǎn)并傳值。
那么在跳轉(zhuǎn)過去的頁面怎樣在<script>中獲取到傳過來的參數(shù)呢?
下面是小編的一個(gè)案例:
//參數(shù)傳出頁面
window.location.href = 'http://m.4tl426be.cn/bcjs/Frameset.aspx?name=' + username + '&tbpwd='+tbpwd;//這里是我要將username和tbpwd作為參數(shù)傳到Frameset.aspx這個(gè)頁面上
一、字符串分割分析法
//參數(shù)接收頁面(Frameset.aspx) <script type='text/javascript' language='javascript'> $(function () { var url = location.search; ////獲取接收到的url中含'?'符后的字串 var request = new Object(); //實(shí)例化一個(gè)對象 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ù)和對應(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)行頁面跳轉(zhuǎn)及傳參后在跳轉(zhuǎn)后的頁面接收到參數(shù)!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php測試程序運(yùn)行速度和頁面執(zhí)行速度的代碼2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. 三個(gè)不常見的 HTML5 實(shí)用新特性簡介4. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問題分析5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. SharePoint Server 2019新特性介紹7. React+umi+typeScript創(chuàng)建項(xiàng)目的過程8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究
