we know , "GET" request , usually behind the parameter in the URL , such as this
http://www.cnblogs.com/season-huang/index ? param = yes & article = 1
where the red part is the parameters in the URL .
So, how to get it through Javascript ? And how a bunch of strings from so I need to find the corresponding values of the parameters it ?
Method One :
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "": decodeURIComponent(results[1]);
}
console.log(getParameterByName("param")) //yes
Let's explain this code it :
1: Define a getParameterByName function , the receiver needs to query parameters key, then return to this parameter value
2: name = name.replace (/ [\ [] /, "\ \ \ ["). replace (/ [\]] /, "\ \ \]");
the role of this code is to " [ " with " \ [ " , the " ] " with " \ ] " , the reason for doing such a conversion is necessary because the following use the name of this variable to construct a regular expression , while [ and ] is in regular keyword , so the need to escape .
3 var regex = new RegExp ("[\ \? &]" + name + "= ([^ & #] *)")
this code is relatively simple, match ? Or & then name then = and non- ( & or # ) .
4 results = regex.exec (location.search); return results == null? "": decodeURIComponent (results [1]);
looking to put together these two , the first to get all location.search query string ( ie, most articles give an example of a URL beginning of the red part ) , then use a regular exec method to match the results , this method returns an array , even in this case , results of this array is ["? params = yes", "yes"]. To note here , since the regex to match the yes part added a grouping parentheses , so the results of the second array (results [1]) to yes.
This function does write very elegant , very powerful. But then, there is a drawback , that every time I need to query a parameter when the need for such a process , structure is regular, matching location.search, return results. But obviously , when we finished loading the page when , URL is fixed and does not become ( without regard to html5 history api), so each time such a process is a waste of resources, it has the following method .
method two
var urlParams;
(window.onpopstate = function() {
var match,
pl = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function(s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
//urlParams的结果
urlParams = {
param: "yes",
article: "1"
}
console.log(urlParams["param"]); // -> "yes"
console.log("article" in urlParams); // -> true
This code is relatively simple, the only thing to note is that pl = / \ + / g, s.replace (pl, "")); reason why there is such a one , because in the URL specification inside, plus sign ( + ) is encoded as a space, all the time in the decode , plus the need to go back to space .
inside this method , when the page load is complete , all of the parameters in the URL will be placed urlParams this object inside . After just need to find the object's attributes can be found in the corresponding result.
in practical work , personal opinion, this method is preferable than the first one .
Method three
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
qs ["param"]; / / yes
qs ["article"]; / / 1
qs ["nothere"]; / / undefined (object)
relatively straightforward , the code will not do here explained . And methods of two , as the result is stored in the object inside qs .
method four
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
If a page is used only occasionally , and the number of bytes of the code have obsessive-compulsive disorder , you can use this method.
Finally , there are some jQuery plugin also implements such a feature. But personally think that this is not a small way written in the form of plug-ins necessary to feel, so it is not listed here , you can own Google .
herein by reference : http://stackoverflow .com/questions/901115/how-can-i-get-query-string-values
article reprint please indicate the source and author wonderful one blossoming - http://www.cnblogs.com/season-huang/ , not for any commercial purposes
没有评论:
发表评论