javascript获取url参数和script标签中获取url参数
url paramter:
//lastest:
var queryStrings=function() {//get url querystring
var params=document.location.search,reg=/(?:^\?|&)(.*?)=(.*?)(?=&|$)/g,temp,args={};
while((temp=reg.exec(params))!=null) args[temp[1]]=decodeURIComponent(temp[2]);
return args;
};
//只取一个:
var queryString=function(key){
return (document.location.search.match(new RegExp("(?:^\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1];
}
var args=queryStrings();
alert(args.name+" | "+args.sex+" | "+args.age);
//测试链接:<a href="?name=abc&sex=男&age=12">test getQueryString</a>
var queryStrings=function() {//get url querystring
var params=document.location.search,reg=/(?:^\?|&)(.*?)=(.*?)(?=&|$)/g,temp,args={};
while((temp=reg.exec(params))!=null) args[temp[1]]=decodeURIComponent(temp[2]);
return args;
};
//只取一个:
var queryString=function(key){
return (document.location.search.match(new RegExp("(?:^\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1];
}
var args=queryStrings();
alert(args.name+" | "+args.sex+" | "+args.age);
//测试链接:<a href="?name=abc&sex=男&age=12">test getQueryString</a>
script paramter:
var getScriptArgs=function(){//获取多个参数
var scripts=document.getElementsByTagName("script"),
script=scripts[scripts.length-1],//因为当前dom加载时后面的script标签还未加载,所以最后一个就是当前的script
src=script.src,
reg=/(?:\?|&)(.*?)=(.*?)(?=&|$)/g,
temp,res={};
while((temp=reg.exec(src))!=null) res[temp[1]]=decodeURIComponent(temp[2]);
return res;
};
var args=getScriptArgs();
alert(args.a+" | "+args.b+" | "+args.c);
//假如上面的js是在这个js1.js的脚本中<script type="text/javascript" src="js1.js?a=abc&b=汉字&c=123"></script>
var getScriptArg=function(key){//获取单个参数
var scripts=document.getElementsByTagName("script"),
script=scripts[scripts.length-1],
src=script.src;
return (src.match(new RegExp("(?:\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1];
};
alert(getScriptArg("c"));
var scripts=document.getElementsByTagName("script"),
script=scripts[scripts.length-1],//因为当前dom加载时后面的script标签还未加载,所以最后一个就是当前的script
src=script.src,
reg=/(?:\?|&)(.*?)=(.*?)(?=&|$)/g,
temp,res={};
while((temp=reg.exec(src))!=null) res[temp[1]]=decodeURIComponent(temp[2]);
return res;
};
var args=getScriptArgs();
alert(args.a+" | "+args.b+" | "+args.c);
//假如上面的js是在这个js1.js的脚本中<script type="text/javascript" src="js1.js?a=abc&b=汉字&c=123"></script>
var getScriptArg=function(key){//获取单个参数
var scripts=document.getElementsByTagName("script"),
script=scripts[scripts.length-1],
src=script.src;
return (src.match(new RegExp("(?:\\?|&)"+key+"=(.*?)(?=&|$)"))||['',null])[1];
};
alert(getScriptArg("c"));
ps:不要在方法中调用此方法,否则可能始终获取的是最后一个js的文件的参数,要在方法中使用,请先放到js加载时就会执行的变量中 保存