Cómo recuperar los parámetros GET de javascript? [duplicar]


Esta pregunta ya tiene una respuesta aquí:

http://domain.com/page.html?returnurl=%2Fadmin

Para js dentro de page.html, ¿cómo puede recuperar GET parámetros?

Para el ejemplo simple anterior, func('returnurl') debería ser /admin

Pero también debería funcionar para querystrngs complejas...

Author: compile-fan, 2011-03-27

17 answers

Con la ventana .objeto location . Este código te da OBTENER sin el signo de interrogación.

window.location.search.substr(1)

De tu ejemplo volverá returnurl=%2Fadmin

EDIT : Me tomé la libertad de cambiar La respuesta de Qwerty , que es realmente buena , y como él señaló, seguí exactamente lo que el OP preguntó:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}

Eliminé la ejecución de la función duplicada de su código, reemplazándola con una variable (tmp ) y también he agregado decodeURIComponent, exactamente como OP pedir. No estoy seguro si esto puede o no ser un problema de seguridad.

O de otra manera con llano para el ciclo, que trabajará incluso en IE8:

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    var items = location.search.substr(1).split("&");
    for (var index = 0; index < items.length; index++) {
        tmp = items[index].split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    }
    return result;
}
 273
Author: Bakudan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-15 01:38:23

window.location.search devolverá todo desde el ? en. Este código a continuación eliminará el ?, use split para separarse en matrices clave/valor, luego asigne propiedades con nombre al objeto params:

function getSearchParameters() {
      var prmstr = window.location.search.substr(1);
      return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}

function transformToAssocArray( prmstr ) {
    var params = {};
    var prmarr = prmstr.split("&");
    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }
    return params;
}

var params = getSearchParameters();

Puede obtener el parámetro de prueba desde http://myurl.com/?test=1 llamando a params.test.

 246
Author: weltraumpirat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-03 18:37:12

tl; dr solución en una sola línea de código usando javascript de vainilla

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})

Esta es la solución más simple. Desafortunadamente no maneja claves multi-valoradas y caracteres codificados.

"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin"  //overriden with last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined

claves multi-valoradasy caracteres codificados?

Vea la respuesta original en ¿Cómo puedo obtener valores de cadena de consulta en JavaScript?

"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]


En su ejemplo, accedería al valor como este:
"?returnurl=%2Fadmin"
> qd.returnurl    // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"
 120
Author: Qwerty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:26

Aquí está la respuesta correcta para 2016:

some = new URLSearchParams("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")
var q = some.get('q') // 'mdn query string'
var ie = some.has('ie') // true
some.append('new','here')

console.log(q)
console.log(ie)
console.log(some)

Https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://polyfill.io/v2/docs/features /

 65
Author: AKnox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-07 15:48:30

Una forma más elegante de hacerlo::)

var options = window.location.search.slice(1)
                      .split('&')
                      .reduce(function _reduce (/*Object*/ a, /*String*/ b) {
                        b = b.split('=');
                        a[b[0]] = decodeURIComponent(b[1]);
                        return a;
                      }, {});
 31
Author: Stefan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-18 18:09:39

Lo hago así (para recuperar un parámetro get específico, aquí 'ParameterName'):

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
 7
Author: lsblsb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 13:02:06

Aquí he hecho este código para transformar los parámetros GET en un objeto para usarlos más fácilmente.

//Get Nav Url
function getNavUrl() {
    //Get Url
    return window.location.search.replace("?", "");
};
function getParameters(url) {
    //Params obj
    var params = {};
    //To lowercase
    url = url.toLowerCase();
    //To array
    url = url.split('&');

    //Iterate over url parameters array
    var length = url.length;
    for(var i=0; i<length; i++) {
        //Create prop
        var prop = url[i].slice(0, url[i].search('='));
        //Create Val
        var value = url[i].slice(url[i].search('=')).replace('=', '');
        //Params New Attr
        params[prop] = value;
    }
    return params;
};
//Call To getParameters
console.log(getParameters(getNavUrl()));
 4
Author: Lucas Serena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 19:13:32
var getQueryParam = function(param) {
    var found;
    window.location.search.substr(1).split("&").forEach(function(item) {
        if (param ==  item.split("=")[0]) {
            found = item.split("=")[1];
        }
    });
    return found;
};
 3
Author: Jonas Sciangula Street,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-14 12:25:28

Este usa regex y devuelve null si param no existe o no tiene valor:

function getQuery(q) {
   return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
 3
Author: Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-01 16:58:44

Si no te importa usar una biblioteca en lugar de implementar tu propia implementación, echa un vistazo a https://github.com/jgallen23/querystring .

 2
Author: thSoft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-28 12:27:16

Esta solución maneja la decodificación de URL:

var params = function() {
    function urldecode(str) {
        return decodeURIComponent((str+'').replace(/\+/g, '%20'));
    }

    function transformToAssocArray( prmstr ) {
        var params = {};
        var prmarr = prmstr.split("&");
        for ( var i = 0; i < prmarr.length; i++) {
            var tmparr = prmarr[i].split("=");
            params[tmparr[0]] = urldecode(tmparr[1]);
        }
        return params;
    }

    var prmstr = window.location.search.substr(1);
    return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();

Uso:

console.log('someParam GET value is', params['someParam']);
 2
Author: Jonah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-14 05:26:24

Mi solución se expande en @tak3r ' s

Devuelve un objeto vacío cuando no hay parámetros de consulta y admite la notación de matriz ?a=1&a=2&a=3:

function getQueryParams () {
  function identity (e) { return e; }
  function toKeyValue (params, param) {
    var keyValue = param.split('=');
    var key = keyValue[0], value = keyValue[1];

    params[key] = params[key]?[value].concat(params[key]):value;
    return params;
  }
  return decodeURIComponent(window.location.search).
    replace(/^\?/, '').split('&').
    filter(identity).
    reduce(toKeyValue, {});
}
 1
Author: gtramontina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-12 08:03:45

Si está usando angularjs, puede usar $routeParams usando ngRoute módulo

Usted tiene que agregar módulo en su aplicación

angular.module('myApp', ['ngRoute'])

Ahora puedes usar service $routeParams

.controller('AppCtrl', function($routeParams) {
  console.log($routeParams); //json object 
}
 1
Author: vusan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-16 09:51:57

Aquí hay otro ejemplo basado en el ejemplo de Kat y Bakudan anterior, pero haciéndolo un poco más genérico.

function getParams ()
{
    var result = {};
    var tmp = [];

    location.search
        .substr (1)
        .split ("&")
        .forEach (function (item) 
        {
            tmp = item.split ("=");
            result [tmp[0]] = decodeURIComponent (tmp[1]);
        });

    return result;
}

location.getParams = getParams;

console.log (location.getParams());
console.log (location.getParams()["returnurl"]);
 1
Author: E Net Arch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-30 22:02:31

Puede utilizar la función de búsqueda disponible en el objeto ubicación. La función de búsqueda da la parte del parámetro de la URL. los detalles se pueden encontrar aquí - http://www.javascriptkit.com/jsref/location.shtml

Tendrá que analizar la cadena resultante para obtener las variables y sus valores, por ejemplo, dividirlas en ' = '

 0
Author: Gaurav Saxena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-27 10:20:07

Para obtener los parámetros como un objeto JSON:

alert(getUrlParameters().toSource())

function explode(delim, str)
{
    return str.split(delim);
}

function getUrlParameters()
{
    var out = {};
    var str = window.location.search.replace("?", "");
    var subs = explode('&', str);
    for(var i = 0; i < subs.length; ++i)
    {
        var vals = explode('=', subs[i]);
        out[vals[0]] = vals[1];
    }
    return out;
}
 0
Author: Randhir Rawatlal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-18 05:09:06

He creado una función Javascript simple para acceder a los parámetros GET desde URL.

Simplemente incluya esta fuente Javascript y podrá acceder a los parámetros get. Por ejemplo: en http://example.com/index.php?language=french , la variable language se puede acceder como $_GET["language"]. Del mismo modo, una lista de todos los parámetros almacenados en una variable $_GET_Params como una matriz. Tanto Javascript como HTML se proporcionan en el siguiente fragmento de código:

<!DOCTYPE html>
<html>
  <body>
    <!-- This script is required -->
    <script>
    function $_GET() {
      // Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
      var href = window.location.href;
	
      // Get the protocol e.g. http
      var protocol = window.location.protocol + "//";
	
      // Get the host name e.g. www.google.com
      var hostname = window.location.hostname;
	
      // Get the pathname e.g. /files/script.php
      var pathname = window.location.pathname;
	
      // Remove protocol part
      var queries = href.replace(protocol, '');
	
      // Remove host part
      queries = queries.replace(hostname, '');
	
      // Remove pathname part
      queries = queries.replace(pathname, '');
	
      // Presently, what is left in the variable queries is : ?v=1.8.7&country=india
	
      // Perform query functions if present
      if (queries != "" && queries != "?") {
	
	    // Remove question mark ?
        queries = queries.slice(1);
	
        // Split all the different queries
        queries = queries.split("&");
		
        // Get the number of queries
        var length = queries.length;
		
        // Declare global variables to store keys and elements
        $_GET_Params = new Array();
        $_GET = {};
	
        // Perform functions per query
        for (var i  = 0; i < length; i++) {
			
          // Get the present query
          var key = queries[i];
			
          // Split the query and the value
          key = key.split("=");
			
          // Assign value to the $_GET variable
          $_GET[key[0]] = [key[1]];
			
          // Assign value to the $_GET_Params variable
          $_GET_Params[i] = key[0];
        }
      }
    }

    // Execute the function
    $_GET();
    </script>
    <h1>GET Parameters</h1>
    <h2>Try to insert some get parameter and access it through javascript</h2>
  </body>
</html>
 0
Author: Chandrashekar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-12 03:15:33