Parámetro Get escaped URL
Estoy buscando un complemento de jQuery que pueda obtener parámetros de URL y soportar esta cadena de búsqueda sin generar el error de JavaScript: "secuencia de URI malformada". Si no hay un plugin de jQuery que soporte esto, necesito saber cómo modificarlo para soportar esto.
?search=%E6%F8%E5
El valor del parámetro URL, cuando se decodifica, debe ser:
æøå
(los caracteres son noruegos).
No tengo acceso al servidor, así que no puedo modificar nada en él.
19 answers
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
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-04-27 06:02:01
A continuación se muestra lo que he creado a partir de los comentarios aquí, así como la corrección de errores no mencionados (como devolver null, y no 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
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
2012-04-10 15:09:01
Lo que realmente quieres es el complemento del analizador de URL de jQuery. Con este plugin, obtener el valor de un parámetro de URL específico (para la URL actual) se ve así:
$.url().param('foo');
Si desea un objeto con nombres de parámetros como claves y valores de parámetros como valores, simplemente llame a param()
sin un argumento, como este:
$.url().param();
Esta biblioteca también funciona con otras urls, no solo con la actual:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Dado que esta es una biblioteca de análisis de URL completa, también puede obtener otra información de la URL, como el puerto especificado, o la ruta, el protocolo, etc.:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
También tiene otras características, echa un vistazo a su página de inicio para más documentos y ejemplos.
En lugar de escribir su propio analizador de URI para este propósito específico que kinda funciona en la mayoría de los casos, use un analizador de URI real. Dependiendo de la respuesta, el código de otras respuestas puede devolver 'null'
en lugar de null
, no funciona con parámetros vacíos (?foo=&bar=x
), no puede analizar y devuelve todos los parámetros a la vez, repite el trabajo si consulta repetidamente la URL para obtener parámetros, etc.
Usa un analizador URI real, no inventes el tuyo propio.
Para aquellos reacios a jQuery, hay una versión del plugin que es pura JS.
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
2012-06-09 01:46:21
Si no sabe cuáles serán los parámetros de URL y desea obtener un objeto con las claves y valores que están en los parámetros, puede usar esto:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Llamando a getParameters() con una url como /posts?date=9/10/11&author=nilbus
devolvería:
{
date: '9/10/11',
author: 'nilbus'
}
No incluiré el código aquí ya que está aún más lejos de la pregunta, pero weareon.net publicado una biblioteca que permite la manipulación de los parámetros en la URL también:
- Entrada de blog: http://blog.weareon.net/working-with-url-parameters-in-javascript /
- Código: http://pastebin.ubuntu.com/1163515 /
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
2013-10-21 18:19:09
Puede utilizar la ubicación nativa del navegador .buscar propiedad:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
Pero hay algunos plugins de jQuery que pueden ayudarte:
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
2009-09-10 07:56:55
Basado en la respuesta de 999 :
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Cambios:
-
decodeURI()
se sustituye pordecodeURIComponent()
-
[?|&]
se añade al principio de la expresión regular
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:45:31
Necesita agregar el parámetro i para hacerlo insensible a mayúsculas y minúsculas:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
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
2012-12-18 14:48:31
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
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
2012-09-10 07:21:03
Por ejemplo , una función que devuelve el valor de cualquier variable de parámetros.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
Y así es como puede usar esta función asumiendo que la URL es,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
Así que en la variable de código anterior "tech" tendrá "jQuery" como valor y la variable "blog" será "jquerybyexample".
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
2013-01-22 08:55:42
¡No deberías usar jQuery para algo como esto!
La forma moderna es utilizar pequeños módulos reutilizables a través de un gestor de paquetes como Bower.
He creado un pequeño módulo que puede analizar la cadena de consulta en un objeto. Úsalo así:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
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
2013-11-15 02:29:13
Después de leer todas las respuestas terminé con esta versión con + una segunda función para usar parámetros como banderas
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
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
2013-05-06 18:22:07
Hay un montón de código con errores aquí y las soluciones regex son muy lentas. Encontré una solución que funciona hasta 20 veces más rápido que la contraparte regex y es elegantemente simple:
/*
* @param string parameter to return the value of.
* @return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex no es la solución definitiva, para este tipo de problema la simple manipulación de cadenas puede funcionar de manera mucho más eficiente. Fuente de código .
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
2013-07-02 01:04:15
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id)
o getURLParameter(Id)
Funciona igual:)
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
2013-08-06 09:31:22
Fragmento de código jQuery para obtener las variables dinámicas almacenadas en la url como parámetros y almacenarlas como variables JavaScript listas para usar con sus scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
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-08-18 08:48:52
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
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
2012-01-05 20:21:19
He creado una función simple para obtener el parámetro URL en JavaScript a partir de una URL como esta:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
SALIDA: 18
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
2012-09-24 16:16:59
En caso de que tengan la url como localhost/index.xsp?a = 1 # algo y necesitas obtener el param no el hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
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
2012-09-25 08:45:05
Ligera modificación a la respuesta de @pauloppenheim , ya que no manejará correctamente los nombres de parámetros que pueden ser parte de otros nombres de parámetros.
Por ejemplo: Si tiene parámetros "appenv" y "env", volver a configurar el valor de "env" puede recoger el valor de "appenv".
Arreglo:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
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
2013-07-30 21:29:16
Esto puede ayudar.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>
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
2012-09-13 01:34:12