1.html:
<a href="2.html?name=geovindu&sex=woman&age=12">test getQueryString</a>
2.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>javascript获取url参数和script标签中获取url参数</title> <script type="text/javascript" src="js1.js?a=abc&b=汉字&c=123"></script> <script type="text/javascript"> //lastest: url paramter: //测试链接:<a href="2.html?name=geovindu&sex=woman&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]; } </script> </head> <body> <div id="urlparamter"></div> <div id="all"></div> <div id="scriptparamter"></div> <div id="allscript"></div> <script type="text/javascript"> var args=queryStrings(); document.getElementById("all").innerHTML=args.name+" | "+args.sex+" | "+args.age+",all"; //alert(args.name+" | "+args.sex+" | "+args.age); var argsname=queryString("name"); var argssex=queryString("sex"); var argsage=queryString("age"); document.getElementById("urlparamter").innerHTML =argsname+","+argssex+","+argsage; </script> </body> </html>
js1.js:
/*http://css.dusystem.com/example/index.html window.location.protocol = "http:" window.location.host = "css.dusystem.com" window.location.pathname = "example/index.html" http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript http://www.cnblogs.com/sohighthesky/archive/2010/01/21/1653126.html http://www.codeproject.com/Tips/574956/How-to-get-URL-and-QueryString-value-in-an-ASP-NET test: <a href="1.html?id=5&type=1&flag=0" title="d">test</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 argsscript=getScriptArgs(); //document.getElementById("scriptparamter").innerHTML =argsscript.a+" | "+argsscript.b+" | "+argsscript.c; alert(argsscript.a+" | "+argsscript.b+" | "+argsscript.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"));
时间: 2024-10-11 20:50:18