How to capture parameters passed by the URL using javascript?

Asked

Viewed 21,883 times

6

How to capture parameters passed by URL (GET method) using javascript? it is also possible to capture parameters passed via POST method?

1 answer

14


The data passed via POST are only available on the server side.
Browser does not pass them to Javascript/client.

The data GET can be read from url. There is no native tool for this as in PHP or Node.js. The method is more or less to read this string tearing her to pieces.

To read the GET/query string from url can be used location.search that gives the part started by the ?. Then you have to group by value key. The query syntax is:

?key=value&other=othersValue& ... etc

The ? starts the string, the & separates each key and value group.

An example would be meusite.com/?lang=pt&page=home. To remove these parameters for an object for example you can do so:

var query = location.search.slice(1);
var partes = query.split('&');
var data = {};
partes.forEach(function (parte) {
    var chaveValor = parte.split('=');
    var chave = chaveValor[0];
    var valor = chaveValor[1];
    data[chave] = valor;
});

console.log(data); // Object {lang: "pt", page: "home"}

Example: http://output.jsbin.com/qawiyiqisu/1/? lang=pt&page=home

Browser other questions tagged

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