简体   繁体   中英

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("&");
      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, eg 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

eg: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM