How to read get request using Javascript?

10,748

Solution 1

Here is a function to parse the query string. Pass it the parameter name and it returns the value.

function getQueryVariable(variable)
{ 
  var query = window.location.search.substring(1); 
  var vars = query.split("&"); 
  for (var i=0;i<vars.length;i++)
  { 
    var pair = vars[i].split("="); 
    if (pair[0] == variable)
    { 
      return pair[1]; 
    } 
  }
  return -1; //not found 
}

Solution 2

Use location.search:

alert(location.search); // will display everything from the ? onwards

You probably want to separate the different variables from the query string so that you can access them by name:

var request = {};
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
  var pair = pairs[i].split('=');
  request[pair[0]] = pair[1];
}

Then you can access it like request['varString'] and that will give you "bla-bla-bla".

Solution 3

Mostly you'd like to handle the parameters passed to your page in the server side, but if you got your reasons why to do it client-side, here's a small script i found:

function gup( name )
{
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
      return "";
   else
      return results[1];
}

i didn't test it, but i'm pretty sure it'll to the job.

just use it like: gup('parameter') and it'll return the parameter value for you.

Share:
10,748
Rella
Author by

Rella

Hi! sorry - I am C/C++ noobe, and I am reading a book=)

Updated on June 19, 2022

Comments

  • Rella
    Rella almost 2 years

    So I have html page called A.html it was called like this from B.html : A.html?varString="bla-bla-bla" Is it correct for sending args to JS? How to parse args from JS?

    (not using any frameworks like Jquery, working in IE6, FireFox 3)