avaweb
在我們平常的javaweb開發中,前臺頁面經常會用到獲取url中的參數,大多數程序員可能直接
用window.location.href 獲取到當前頁面的url,然后再用substring去截取字符串,這樣的話很麻煩。
當然我上面所說的是在html的文件中,如果你是用的jsp的話,那就很簡單了。用el表達式我們可以很輕松的獲取url中的參數:${param.paramName}
好了,言歸正傳,那如何在html中獲取url中的參數了?
我們可以單獨封裝一個函數來達到這個目的。以后只要是要獲取url的參數,直接調用這個函數就可以了。
function get_param(name, url){
if(!url) url = window.location.href;
name = name.replace(/[\[\]]/g,"\$&");
var regex =newRegExp("[?&]"+ name +"(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if(!results) return null;
if(!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g," "));
}
我在后續的文章中,會分享更多更實用的開發小技巧給大家,希望大家多多關注!
const urlSearchParams = new URLSearchParams(window.location.search);
const queryParams = Object.fromEntries(urlSearchParams.entries());
console.log(queryParams);//成功轉換成對象
注意看url中的查詢值哦
const urlSearchParams = new URLSearchParams(window.location.search);
const value = urlSearchParams.get("a");
console.log(value);
拿來吧你
天碰到要在一個頁面獲取另外一個頁面url傳過來的參數,一開始很本能的想到了用 split(“?”)這樣一步步的分解出需要的參數。
喜歡的朋友可以測試下,希望對大家有所幫助!
js方法一:正則分析法,指定參數名獲取值。
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;
}
// 這樣調用:
// http://orzhtml.github.io?a=1&b=2&c=3
console.log(getQueryString("a"));
console.log(getQueryString("b"));
console.log(getQueryString("c"));
結果截圖:
下面舉一個例子:
若地址欄URL為:abc.html?id=123&url=http://orzhtml.github.io
那么,但你用上面的方法去調用:alert(getQueryString("url"));
則會彈出一個對話框:內容就是 http://orzhtml.github.io
如果用:alert(getQueryString("id"));那么彈出的內容就是 123 啦;
當然如果你沒有傳參數的話,比如你的地址是 abc.html 后面沒有參數,那強行輸出調用結果有的時候會報錯:
所以我們要加一個判斷 ,判斷我們請求的參數是否為空,首先把值賦給一個變量:
var myurl= getQueryString("url");
if(myurl != null && myurl.toString().length>1) {
alert(myurl);
}
js方法二:獲取所有參數這樣就不會報錯了,結果返回始終會是一個對象!
function GetRequest(){
var url = location.search;//獲取url中"?"符后的字串
var theRequest ={};
if(url.indexOf("?")!=-1){
var str = url.substr(1);
strs = str.split("&");
for(var i =0; i < strs.length; i ++){
theRequest[strs[i].split("=")[0]]= unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
// 這樣調用
// http://orzhtml.github.io?a=4&b=5&c=6
var Request = {};
Request = GetRequest();
console.log(Request);
console.log(Request['a']);
console.log(Request['b']);
console.log(Request['c']);
結果截圖:
本文內容均屬個人原創作品,轉載此文章須附上出處及原文鏈接。
加關注,定時推送,互動精彩多,若你有更好的見解,歡迎留言探討!
*請認真填寫需求信息,我們會在24小時內與您取得聯系。