How to read Querystring parameters in Javascript

Asked

Viewed 1,251 times

2

How do I collect arguments from an HTML page?

Like I tried to use like C# / ASP.NET:

var conteudo = Response.QueryString["usuario"];

Considering a query string as:

/default.html?usuario=pt

Then he would let me know what was after the "=".

How to get the value with Javascript?

  • in case what he would return would be the value pt

  • 2

    recommend you read the [Ask]. The title of your question is appealing and does not describe your problem

  • was bad but you know how I use queryString?

1 answer

4


function getUrlParameters(parameter, staticURL, decode){
   /*
    Function: getUrlParameters
    Descrição: Obtem o valor dos parâmetros da URL atual ou URL estática
    Author: Tirumal
    URL: www.code-tricks.com
   */
   var currLocation = (staticURL.length)? staticURL : window.location.search,
       parArr = currLocation.split("?")[1].split("&"),
       returnBool = true;

   for(var i = 0; i < parArr.length; i++){
        parr = parArr[i].split("=");
        if(parr[0] == parameter){
            return (decode) ? decodeURIComponent(parr[1]) : parr[1];
            returnBool = true;
        }else{
            returnBool = false;            
        }
   }

   if(!returnBool) return false;  
}

That code was taken from the website Code-Tricks, you can use it as follows:

From the current window location:

var parametro1 = getUrlParameters("nomeDoParametro", "", true);

From a static url:

var parametro1 = getUrlParameters("usuario", "http://www.exemplo.com/default.html?usuario=pt", true);

Fiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.