JavaScript 获取地址栏指定参数
程序员文章站
2022-03-10 21:48:26
...
假如当前地址栏链接为:https://test.com/?type=students&page=3
//获取参数方法1
function UrlSearch()
{
var name,value;
var str=location.href; //取得整个地址栏
var num=str.indexOf("?");
str=str.substr(num+1); //取得所有参数 stringvar.substr(start [, length ]
var arr=str.split("&"); //各个参数放到数组里
for(var i=0;i < arr.length;i++){
num=arr[i].indexOf("=");
if(num>0){
name=arr[i].substring(0,num);
value=arr[i].substr(num+1);
this[name]=value;
}
}
}
var UrlSearch=new UrlSearch(); //实例化
alert(UrlSearch.type); //students
alert(UrlSearch.page); //3
alert(UrlSearch.studentid); //undefined
//获取参数方法2
function getParameter(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) {
return decodeURI(r[2])
}
return null
}
alert(getParameter('type')); //students
alert(getParameter('page')); //3
alert(getParameter('studentid')); //null
原文链接:https://tiicle.com/items/340/javascript-to-get-the-address-bar-specified-parameters
上一篇: MySQL 链接参数说明