2

I'm noob to JavaScript and want to use Prototype JS Framework to get some URL parameters. Imagine I have the following URL on my current browser:

http://www.somewhere.com?param=abc

how can I get the value of 'param' using any function or utility of Prototype JS ?

1

3 Answers 3

11

Prototype.js DOES provide a utility:

uri.toQueryParams();
Sign up to request clarification or add additional context in comments.

Comments

4

You really don't need Prototype for this:

function get_param(param) {
   var search = window.location.search.substring(1);
   var compareKeyValuePair = function(pair) {
      var key_value = pair.split('=');
      var decodedKey = decodeURIComponent(key_value[0]);
      var decodedValue = decodeURIComponent(key_value[1]);
      if(decodedKey == param) return decodedValue;
      return null;
   };

   var comparisonResult = null;

   if(search.indexOf('&') > -1) {
      var params = search.split('&');
      for(var i = 0; i < params.length; i++) {
         comparisonResult = compareKeyValuePair(params[i]); 
         if(comparisonResult !== null) {
            break;
         }
      }
   } else {
      comparisonResult = compareKeyValuePair(search);
   }

   return comparisonResult;
}

var param_value = get_param('param'); //abc

6 Comments

hi jacob thank you for your reply, but i want to know is there any utility provided by Prototype js for this requirement ?
@dprima There is no utility that does this that I know of.
oh i see, thx jacob, both your answer and tim's below were true, but because you're the first, ill mark your answer as accepted
It may be worth calling decodeURIComponent on key_value[1] and ideally on key_value[0] before comparing it to the param.
@MikeSamuel I refactored the entire function to be a whole lot cleaner. I provided the original answer to this question over a year ago, so this should be a lot better... Any comments on the updated code are welcome! :)
|
4

Expanding on Scott's answer: to put the value of the URL variable 'param' into the javascript variable 'x' you would use Prototype like so:

x = document.URL.toQueryParams().param;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.