Take parameters from the URL

Asked

Viewed 16,847 times

0

Guys I have the following url: http://localhost:27903/detalhes.aspx?id=3014953&stars=70 I need to get the separate parameters, id and Stars, some hint I’ve tried everything, follow my code:

$('tbody#corpo2').append(            
'<tr><td style="border:solid 1px #ccc; text-align:center">' + location.search.substring(4) + '</td>'
+ '<td style="border:solid 1px #ccc">' + "teste" + '</td>'
+ '<td style="border:solid 1px #ccc">' + location.search.substring(17).replace("s=", "").replace("=","") + ' </td>' + '</tr>');
});
  • 1

    Note: Location.search.substring(4) takes everything up to the end of the URL, it would be possible to limit it to pick up the &?

5 answers

3

Here’s how to take all the parameters and put into an object:

//Array de parametros 'chave=valor'
var params = window.location.search.substring(1).split('&');

//Criar objeto que vai conter os parametros
var paramArray = {};

//Passar por todos os parametros
for(var i=0; i<params.length; i++) {
    //Dividir os parametros chave e valor
    var param = params[i].split('=');

    //Adicionar ao objeto criado antes
    paramArray[param[0]] = param[1];
}

To get a value: paramArray['chave']

3


This way it is possible to pick up the parameters sent via GET.

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); 

0

You can take parameters from the url using javascript. Using the Url :http://localhost:27903/details.aspx? id=3014953&Stars=70 as an example :

 <script>
        //Acessamos a funcao passando o parametros que queremos o valor do seu retorno .Ex: o parametro [stars]

 function getParameter(theParameter) {
            var params = window.location.search.substr(1).split('&');

            for (var i = 0; i < params.length; i++) {
                var p = params[i].split('=');
                if (p[0] == theParameter) {
                    return decodeURIComponent(p[1]);
                }
            }
            return false;
            }
            var valorHidSelProduto = getParameter('stars')
            alert(stars);

    </script>

-2

var url_string = window.location.href;
var url = new URL(url_string);
var data = url.searchParams.get("stars"); //pega o value

-5

I pick up via PHP and transmit to Javascript

<script>
Valor = <? $_GET[Valor] ?>;
Parametro_GET = <? $_GET[Parametro_GET] ?>;
<script>
  • 1

    This only works if the page is PHP, which is not the case.

Browser other questions tagged

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