How to catch parameters passed by URL
(GET Method) using javascript? is it also possible to capture parameters passed via POST method?
How to catch parameters passed by URL
(GET Method) using javascript? is it also possible to capture parameters passed via POST method?
Data that is passed via POST is only available on the server side. The browser does not pass them to the JavaScript / client.
GET data can be read from url
. There is no native tool for this like in PHP or Node.js . The method is more or less read this string splitting it into pieces.
To read the GET / query string from url
you can use location.search
that gives the part started by ?
. Then you have to group by key value. The query syntax is:
? key = value & otroChave = otherValue & ... etc
?
starts string , &
separates each key group and value.
An example would be meusite.com/?lang=pt&page=home
. To remove these parameters for an object for example can be done like this:
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"}