2019獨角獸企業重金招聘Python工程師標準>>>
JavaScript獲取地址欄中的鏈接參數
?
?
<script type="text/javascript">
?? ?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;
?? ?}
?? ?//http://192.168.1.1:8083/test/upload2.jsp?id=9&name=apple
?? ?var val=getUrlParam('id'); //輸出177
?? ?var name=getUrlParam('name'); //輸出177
?? ?
?? ?console.log(name)
?? ?console.log(val)
</script>
怎么獲取url地址欄參數、?
參考這篇博客http://caibaojian.com/177.html
?
原文鏈接:http://caibaojian.com/177.html
假設頁面的地址是這樣子的。http://caibaojian.com/p/165 ,那么我要獲取最后的一個數字165,可以通過這樣子的代碼
var url= window.location.href; var index = url.substring(url.lastIndexOf('/') + 1);
但是這樣子有缺陷,假如我獲取到的地址不是這樣子的形式,而是http://caibaojian.com/tools的話,那么這個index的值就不是一個數字了。
解決方案
js獲取瀏覽器地址欄參數、下面這種可能會更好呢?·
//code from http://caibaojian.com/177.html var lastBit = url.substring(url.lastIndexOf('/') + 1).match(/[^\/]*$/)[0]; var lastDigits = url.substring(url.lastIndexOf('/') + 1).match(/[0-9]*$/)[0]; // 獲取的是數字部分
獲取查詢值
JavaScript版:
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; } //獲取http://caibaojian.com/?p=177.html的p值 getUrlParam('p'); //輸出177
jQuery版:
<script type="text/javascript"> (function($){ $.getUrlParam = function(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r!=null) return unescape(r[2]); return null; } })(jQuery); $(function(){ alert(window.location.href); alert($.getUrlParam('page')); }) </script>
http://www.caibaojian.com/front?page=5
當一個頁面的地址是上面這個,那么我們使用了上面的jQuery代碼,就會彈出一個數字5了。
內容擴展
對于像下面這樣的網址
js獲取url后面的參數,http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere
我們可以用javascript獲得其中的各個部分
1, window.location.href-----------整個URl字符串(在瀏覽器中就是完整的地址欄)
本例返回值: http://www.caibaojian.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere
2,window.location.protocol---------URL 的協議部分
本例返回值:http:
3,window.location.host----------URL 的主機部分
本例返回值:www.caibaojian.com
4,window.location.port-----URL 的端口部分
如果采用默認的80端口(update:即使添加了:80),那么返回值并不是默認的80而是空字符
本例返回值:""
5,window.location.pathname(URL 的路徑部分(就是文件地址))
本例返回值:/fisker/post/0703/window.location.html
post地址欄帶參數,6,window.location.search-------查詢(參數)部分
除了給動態語言賦值以外,我們同樣可以給靜態頁面,并使用javascript來獲得相信應的參數值
本例返回值:?ver=1.0&id=6
7,window.location.hash-------錨點
本例返回值:#imhere
推薦文章
- jquery 對 Json 的各種遍歷
- jQuery API 中文手冊改版
- jQuery+JSONP通過調用蝦米接口實踐
- jQuery on()方法
- jquery mobile使用和感受
來源:前端開發博客