Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read get request using Javascript?

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)

like image 211
Rella Avatar asked Nov 17 '10 20:11

Rella


3 Answers

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 
}
like image 106
Evan Mulawski Avatar answered Oct 14 '22 15:10

Evan Mulawski


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".

like image 24
casablanca Avatar answered Oct 14 '22 15:10

casablanca


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.

like image 33
Dimor Avatar answered Oct 14 '22 15:10

Dimor