Instance 1
The code is as follows |
Copy Code |
function getquerystring (name) { var reg = new RegExp ("(^|&)" + name + "= ([^&]*) (&|$)"); var r = window.location.search.substr (1). Match (REG); if (R!= null) Return unescape (r[2]); return null; }
Call method
Alert (getquerystring ("parameter name 1")); Alert (getquerystring ("parameter Name 2")); Alert (getquerystring ("parameter name 3")); |
such as: Geturlparam ("id").
This method constructs a regular expression to match the URL parameter that needs to be queried, Location.search is obtained to the query string part of the URL. The advantage of this method is concise, the disadvantage is that each need to parse the string to find, multiple queries the same parameter inefficient, so there is the following method.
Get URL reference value method two
code is as follows |
copy code |
<span style= "FONT-SIZE:16PX;" ><script language= "JavaScript" > function Getrequest () { var url = location.search; Get the "?" in the URL String after the character var therequest = new Object (); if (Url.indexof ("?")!=-1) { var str = URL.SUBSTR (1); STRs = Str.split ("&"); for (var i = 0; i < strs.length i + +) { Therequest[strs[i].split ("=") [0]]=unescape (Strs[i].split ("=") [1]); } } return therequest; } </Script></span>
|
This call:
The code is as follows |
Copy Code |
<script language= "JavaScript" > var Request = new Object (); Request = Getrequest (); var parameter 1, Parameter 2, parameter 3, parameter n; Parameter 1 = request[' parameter 1 ']; Parameter 2 = request[' parameter 2 ']; Parameter 3 = request[' parameter 3 ']; Parameter n = request[' parameter n ']; </Script> |
The use of closures and regular expressions to implement
The code is as follows |
Copy Code |
var geturlparam = function () { var args = null; return function (name) { if (a RGS = = null) { if (Location.search = = "") return ""; var queryarray = location.search.substring (1). Split ("&"); var i; args = {}; for (i = 0;i < queryarray.length;i++) { var match = Queryarray[i].match ([^=]+) = ([^=]+)/); if (match!== null) { args[match[1]] = match[2]; } } } return args[name] = = undefined? "": Args[name]; }; } (); |
This method utilizes the function closure of JS to save the URL parameters in a args variable within an anonymous function, and no method can access the variable except through Geturlparam. And only the first time to get the URL parameter to parse the URL, then directly from the variable args read.