Código de JavaScript - Obtener los parámetros de llamada a una página web

Imágen de perfil
Val: 64
Ha aumentado 1 puesto en JavaScript (en relación al último mes)
Gráfica de JavaScript

Obtener los parámetros de llamada a una página webgráfica de visualizaciones


JavaScript

Actualizado el 24 de Noviembre del 2020 por Aitor (6 códigos) (Publicado el 10 de Noviembre del 2020)
1.501 visualizaciones desde el 10 de Noviembre del 2020
Obtener los parámetros con los que se ha realizado la llamada a la página web procedentes de un botón <submit> en un formulario por ejemplo enviados con el método "GET" o sea que son visibles en la URL en el navegador.
Es un ejemplo de código javascript que captura estos datos clave:valor con los que luego se pueden realizar otras funciones basándose en los datos recibidos.
Está escrito en puro javascript y no utiliza ninguna librería (no se utiliza Jquery).

1.1
estrellaestrellaestrellaestrellaestrella(1)

Actualizado el 24 de Noviembre del 2020 (Publicado el 10 de Noviembre del 2020)gráfica de visualizaciones de la versión: 1.1
1.502 visualizaciones desde el 10 de Noviembre del 2020
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!DOCTYPE html>
<html>
    <head>
        <title>OBTENER LOS ARGUMENTOS DE ENTRADA GET HTML</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <!-- this code can be saved in a separate file in a subdir js with a name like yourscript.js  -->
        <!-- linked with <script src="./js/yourscript.js"></script>       -->
        <script>
        	function sendMail(subject, message) {
        		let link = "mailto:anybody@mail.com" + "?subject=" + encodeURIComponent(subject) + "&body=" + encodeURIComponent(message);
                //console.log(message);
                //console.log("LINK:\r\n"+link);
        		window.location.href = link;
        	}
        	function $_GET() {
        		//===========================================
        		//auxiliary functions declared previously
        		//===========================================
        		const getURLParameters = url =>
        		(url.match(/([^?=&]+)(=([^&]*))/g) ||[]).reduce(
        			(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
        			{}
        		);
        		//===============================================
        		// Main code
        		//===============================================
        		//get the arguments
        		//let array_param = param();
        		let array_param = getURLParameters(window.location.href); //window.location.search.substring(1)  window.location.href
        		let array_keys =[];
        		array_keys = Object.keys(array_param);
        		if ((array_keys.length=== 0) || (array_keys[0]==="")) {
        			let body = document.getElementsByTagName("body")[0];
        			let texto = document.createTextNode("There are not arguments to capture in the call to this web page ...");
        			body.appendChild(texto);
        		} else {
        			console.table(array_param);
        			console.table(array_keys);
        			let body = document.getElementsByTagName("body")[0];
        			let texto = document.createTextNode("These fields have been received from a form submit in a web page......");
        			body.appendChild(texto);
        			//show the arguments received in a table with 2 columns key:value
        			// Create the elements <table> <thead> <tbody>
        			let tabla = document.createElement("table");
        			//creating the header of the table
        			let tblHeader = document.createElement("thead");
        			let fila = document.createElement("tr");
        			let celda = document.createElement("td");
        			let textoCelda = document.createTextNode("key");
        			celda.appendChild(textoCelda);
        			fila.appendChild(celda);
        			//
        			celda = document.createElement("td");
        			textoCelda = document.createTextNode("valor");
        			celda.appendChild(textoCelda);
        			fila.appendChild(celda);
        			//
        			tblHeader.appendChild(fila);
        			tabla.appendChild(tblHeader);
        			//Create the body of the table
        			let tblBody = document.createElement("tbody");
        			// Creating the cells of the table
        			//loop to read the arguments
        			for (let i = 0, num_elements = array_keys.length; i < num_elements; i++) {
        				// Create a row element <tr> of the table
        				let fila = document.createElement("tr");
        				// Create a <td> element and and create a text node with the content
        				// add the textnode inside the <td> element
        				// place the <td> element at the end of the table row
        				let celda = document.createElement("td");
        				let textoCelda = document.createTextNode(array_keys[i]);
        				celda.appendChild(textoCelda);
        				fila.appendChild(celda);
        				//
        				celda = document.createElement("td");
                        //decodeURIComponent(encoded.replace(/\+/g,  " "));
        				textoCelda = document.createTextNode(decodeURIComponent(array_param[array_keys[i]].replace(/\+/g,  " ")));
        				celda.appendChild(textoCelda);
        				fila.appendChild(celda);
        				// add the row to the end of the table (at the end of the tblbody element)
        				tblBody.appendChild(fila);
        			}
        			// position the <tbody> element below the <table> element
        			tabla.appendChild(tblBody);
        			// appends <table> into <body>
        			body.appendChild(tabla);
        			// modifies the "border" attribute of the table and sets it to "2";
        			tabla.setAttribute("border", "2");
        			tabla.setAttribute("font-size", "20");
        			textoCelda = document.createTextNode("This data can be saved in a database table on MySQL server or send an email with it or redirect to another web");
        			body.appendChild(textoCelda);
        			//========================================================================================
        			//example: send an email with data recieved with the user email client (outlook, etc..)
        			let mensaje = "These fields have been received from a form submit in a web page......\r\n";
        			//loop to read the arguments
        			for (let i = 0, num_elements = array_keys.length; i < num_elements; i++) {
        				mensaje += array_keys[i]+":\r\n";
        				mensaje += decodeURIComponent(array_param[array_keys[i]].replace(/\+/g,  " "))+"\r\n";
        			}
        			//execute function to send an email
        			sendMail("Your Default Email Subject", mensaje);
        			//========================================================================================
        		}
        	}
        </script>
        <script>
        	// Execute the function
        	$_GET();
        </script>
    </body>
</html>



Comentarios sobre la versión: 1.1 (1)

Imágen de perfil
11 de Noviembre del 2020
estrellaestrellaestrellaestrellaestrella
Muy bueno!!!
Responder

Comentar la versión: 1.1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s6717