获取地址栏URL中参数, getQuerySting()方法
今天同事用的以前的獲取url地址參數獲取不到.以前的方法失效了.后面發現是正則表達式bug:
第一種獲取方法(針對普通情況的一般夠用):
function getQueryString(name) {var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");var r = window.location.search.substr(1).match(reg);var q = window.location.pathname.substr(1).match(reg_rewrite);if(r != null){return unescape(r[2]);}else if(q != null){return unescape(q[2]);}else{return null;} }第二種獲取方法:
這樣的url地址獲取不到:file:///Users/wanghong/work/ziku/youle/dist/index.html?sourceType=Tsingtao_beer_activity#/welcome?toPath=file%3A%2F%2F%2FUsers%2Fwanghong%2Fwork%2Fziku%2Fyoule%2Fdist%2Findex.html%3FsourceType%3DTsingtao_beer_activity%23%2F /*** 獲取指定的URL參數值* URL:http://www.quwan.com/index?name=tyler* 參數:paramName URL參數* 調用方法:getParam("name")* 返回值:tyler*/ function getParam(paramName) {paramValue = "", isFound = !1;if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() == paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++}return paramValue == "" && (paramValue = null), paramValue }
大家都嘗試一下.元宵節快樂
3月5號后端了發現bug
我們的URL地址:http://localhost:8081/#/welcome?toPath=http%3A%2F%2Flocalhost%3A8081%2F%23%2F%3FsourceType%3DTsingtao_beer_activity
還是獲取不到sourceType參數
咨詢了群里的守候,,提供了getUrlPromt()了方法
function getUrlPrmt(url) {
? ? ? ? url = url ? url : window.location.href;
? ? ? ? let _pa = url.substring(url.indexOf('?') + 1), _arrS = _pa.split('&'), _rs = {};
? ? ? ? for (let i = 0, _len = _arrS.length; i < _len; i++) {
? ? ? ? ? ? let pos = _arrS[i].indexOf('=');
? ? ? ? ? ? if (pos == -1) {
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? ? ? let name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1));
? ? ? ? ? ? _rs[name] = value;
? ? ? ? }
? ? ? ? return _rs;
? ? }
name我這里的方法寫法應該寫成這樣getUrlPrmt(getUrlPrmt(location.href).toPath).sourceType
?
vue中的跳轉寫法:
this.$router.push({ path: '/register', query: { sourceType: window.getUrlPrmt(window.getUrlPrmt(location.href).toPath).sourceType }
謝謝守候大牛的方法.
轉載于:https://www.cnblogs.com/luosiding/p/8494922.html
總結
以上是生活随笔為你收集整理的获取地址栏URL中参数, getQuerySting()方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CSS公共清除浏览器默认样式
- 下一篇: Phython 3 笔记2 —— 基础语