Explain to me this snippet of JavaScript code
Can anyone explain this code snippet to me?
<script type="text/javascript">
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split(开发者_Go百科"&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
document.write(koko);
document.write("<br>");
document.write(hu);
This is a function to extract variables from the document's query string, e.g. if the document's location is
example.com/test.htm?koko=123
querySt("koko")
will return 123
.
As a side note, the function should use local variables to prevent polluting the global name space:
var hu = window.location.search.substring(1);
var gy = hu.split("&");
...
for (var i = 0; i < gy.length; i++) {
The function is searching for a specified parameter in the query string an does return its value.
Imagine a url like this http://www.my.org/pg.htm?user=2&role=admin
function querySt(ji) {
// Gets all request parameters at client-side (QueryString)
// hu = ?user=2&role=admin
var hu = window.location.search.substring(1);
// Gets an array of substrings splitted by &
// gy[0] = user=2
// gy[1] = role=admin
var gy = hu.split("&");
// Iterate through the string array
for (i = 0; i < gy.length; i++) {
// Split into key/value pair
// ft[0] = 'user'
// ft[1] = '2'
ft = gy[i].split("=");
// See wether the key is 'koko'
if (ft[0] == ji) {
// return '2' if so
return ft[1];
}
}
}
var user= querySt("user");
document.write(user);
document.write("<br>");
document.write(hu);
This would print out 2 in this case. Hu
would only printed out if defined outside the scope of the function querySt
.
As far as I can see, the code gets the query string part of the URL
e.g: http://domain.com?querystparam1=somwthing&querystringparam2=somethingeles....
the query string part is ?querystparam1=somwthing&querystringparam2=somethingeles
hu contains everything but the question mark sign.. then an array en created from the rest split by the & sign, and then loop through the array and searching for koko and returns the value of the koko.
精彩评论