使用jquery獲取url及url引數的方法
阿新 • • 發佈:2020-08-25
一、獲取url及url引數的方法
若獲取地址http://localhost:8080/index.html?id=132
中的id的值,只需要,在js檔案中加入下面程式碼(為jq擴充套件方法getUrlParam ) 便可以通過方法$.getUrlParam('id')
獲取URL的資料
//獲取url中的引數 function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標引數的正則表示式物件 var r = window.location.search.substr(1).match(reg); //匹配目標引數 if (r != null) return unescape(r[2]); return null; //返回引數值 } alert(getUrlParam('id'));
二、獲取url的中文引數
function getUrlParameter(name){ name = name.replace(/[]/,"\[").replace(/[]/,"\[").replace(/[]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS );var results = regex.exec(window.parent.location.href); if( results == null ) return ""; else { return results[1]; } }; var urlid =decodeURI(getUrlParameter("followName")) 轉碼將解碼方式unscape換為decodeURI,將中文引數獲取 console.log(urlid)
三、url拼接引數格式
http://www.yanggb.com?flag=1&type=normal&role=customer
通過上面的例子就可以看出,第一個引數需要以【?】開頭,然後是引數名,然後是【=】,然後是引數值。 第二個引數開始則需要以【&】開頭,然後是引數名,然後是【=】,然後是引數值。
例項:
// 帶標題傳參跳轉 function url_title(title) { window.location.href = "new_target.html?title=" + title; }