一、 通過window.location獲取各項參數
1、獲取頁面完整的url
url = window.location.href;
2、獲取頁面的域名
host = window.location.host;
host2=document.domain;
應用場景:頁面跳轉,開發環境和測試環境域名不同,所以需要動態獲取后進行拼接跳轉的url。
二、javascript正則獲取url中的參數
1、通過substr配合split獲取
//正則獲取url中的參數 function URL_Request(strName) { var strHref = document.location.toString(); var intPos = strHref.indexOf("?"); var strRight = strHref.substr(intPos + 1); //==========獲取到右邊的參數部分 var arrTmp = strRight.split("&"); //=============以&分割成數組 for (var i = 0; i < arrTmp.length; i++) //===========循環數組 { var dIntPos = arrTmp[i].indexOf("="); var paraName = arrTmp[i].substr(0, dIntPos); var paraData = arrTmp[i].substr(dIntPos + 1); if (paraName.toUpperCase() == strName.toUpperCase()) { return paraData; } } return ""; }
使用:
var pbtradeId=URL_Request("tradeId");
2、通過split獲取【update20170503】
function getQueryString(str, key) { if(str) { var queryString = str.split('?')[1] || ''; var arr = queryString.split('&') || []; for(var i = 0; i<arr.length; i++) { var keyString = decodeURIComponent(arr[i].split('=')[0]); var valueString = decodeURIComponent(arr[i].split('=')[1]); if(key === keyString) { return valueString; } } return; } else { return; } } getQueryString(location.search, 'pageId');
本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/6139998.html有問題歡迎與我討論,共同進步。