Skip to main content

URL Parameters & JavaScript


Diogenes Painting by Jean Leon Gerome
Today I was in need of a simple solution to get targeted parameters to a HTML page
I'm in a platform that only accepts a page as home page HTML. In my case my login page.
I needed that if the login had not success, then one message would be passed to this same page be reloaded,  reading and showing  the message.
I did not want to create a second page that is always overlooked when changing the layout or css.

After a little search I wrote the follow code:

to use, create a HTML file like: parametro.html

open with your browser, type something like:

file:///yourfolder/parametro.html?param=Hello World&param2=21/12/1966



<!DOCTYPE HTML>
<HTML LANG="pt-br">
<HEAD>
<SCRIPT>
/**
 * Example of how to read the parameters of 
 * a URL when loading a page using javascript
 * @author Nivio dos Santos
 * @version 1.0
 */

/**
 * Creating namespace in order to avoid naming conflict.
 */
nivio = function(){};
nivio.context = function(){};


/**
 * Static method that can be triggered 
 * when loading the page capturing the parameters.
 */
nivio.context.pageLoaded = function() 

var indice = document.URL.indexOf("?"); 
if(indice > -1)
{
nivio.context.params = new nivio.context.ObjParam();

// shortcut reference
var objParam = nivio.context.params;

// SEPARATE MESSAGE 
var message = document.URL.substr(indice+1); 

// SEPARATE PARAMETERS
var tuples = message.split("&"); 
for(var i=0;i<tuples.length;i++)
{
var param = tuples[i].split("=");
if( param.length > 1)
{
objParam.addParam( param[0], param[1] );
}
else
{
objParam.addParam( param[0], '' );
}
}
}


/**
 * Class to hold the parameters
 * @constructor
 * @this {ObjParam}
 */
nivio.context.ObjParam = function(){};

/**
 * Creates a new Circle from a diameter.
 *
 * @this {ObjParam}
 * @param {String} key to parameter value
 * @param {String} value
 */
nivio.context.ObjParam.prototype.addParam = function(key,value)
{
    this.keys = this.getKeys();
this.keys.push( key );
this[key] = decodeURIComponent(value);
}

/**
 * Get list of keys.
 * @this {ObjParam}
 * @return {Array<String>} The new Circle object.
 */
nivio.context.ObjParam.prototype.getKeys = function()
{
if( this.keys == null || this.keys == undefined )
{
this.keys = new Array();
}
return this.keys;
}

/**
 * Get  key associated parameter value
 * @this {ObjParam}
 * @return {String} 
 */
nivio.context.ObjParam.prototype.getParam = function(key)
{
return this[key];
}


/**
 * Teste
 */
function teste()
{
    var texto="";
    var objParam = nivio.context.params;
    var keys = objParam.getKeys();
for(var i=0;i<keys.length;i++)
{
texto = texto +"<br>"+ keys[i] + "=" + objParam.getParam( keys[i] );
}

var areaT = document.getElementById("areateste");
areaT.innerHTML = texto;
}
</SCRIPT>
</HEAD>
<BODY onload="nivio.context.pageLoaded()">

<INPUT TYPE="BUTTON" VALUE="TESTE" ONCLICK="teste()">
<HR>
<DIV ID="areateste">
</BODY>
</HTML>


Comments

Popular posts from this blog

CÓDIGOS UNICODE PARA CARACTERES ESPECIAIS

A/a á \u00e1 à \u00e0 â \u00e2 ã \u00e3 ä \u00e4 Á \u00c1 À \u00c0 Â \u00c2 Ã \u00c3 Ä \u00c4 E/e é \u00e9 è \u00e8 ê \u00ea ê \u00ea É \u00c9 È \u00c8 Ê \u00ca Ë \u00cb I/i í \u00ed ì \u00ec î \u00ee ï \u00ef Í \u00cd Ì \u00cc Î \u00ce Ï \u00cf O/o ó \u00f3 ò \u00f2 ô \u00f4 õ \u00f5 ö \u00f6 Ó \u00d3 Ò \u00d2 Ô \u00d4 Õ \u00d5 Ö \u00d6 U/u ú \u00fa ù \u00f9 û \u00fb ü \u00fc Ú \u00da Ù \u00d9 Û \u00db Consoantes ç \u00e7 Ç \u00c7 ñ \u00f1 Ñ \u00d1 Símbolos & \u0026 ' \u0027 Ʃ \u01a9 ° \u00b0 ª \u00aa ° \u00b0 ➕ \u2795 ➖ \u2796 ➗ \u2797 ✓ \u2713 ✗ \u2717

Parsing XML with namespace in Java

Introduction Yesterday, again, I needed parser a XML stream using Java. Then I went to Google try to find a exemple code. Because I needed the value of two specific fields, TAGs, I decided use XPATH to get directly this values. How ever, I needed do several tried until get a result. Keywords JAVA, XML, NAMESPACE, XML PARSE; Article I will show how to read XML without namespace and after we will read a XML streams with namespaces. This is the first XML that I have used in this example without namespaces <?xml version="1.0" encoding="UTF-8"?> <root>   <head>     <title>My Book</title>   </head>   <bookreview>     <title>This is a book about special girls</title>     <girls>       <girl>         <name>Mata Hari</name>       </girl>       <girl>          <name>Belle de Jour</name>       </girl>       <girl>          <name&

Neurônio Artificial Conceito

Outro dia conversando sobre redes neurais, consciência, inteligência artificial, percebi que estamos tão cercados e acostumados com tecnologia que em muitos cenários já estamos vivenciando a “Era da magia” onde as coisas funcionam mas o conhecimento de como funcionam está se perdendo. As máquinas acabam nos passando a sensação de serem seres vivos, simulando inteligência e comportamentos. Esta postagem descreve o conceito de um neurônio artificial para dar uma base às próximas postagens, porém com uma abordagem mais palpável, sem usar chips, transistores, ou outros elementos tecnológicos que fogem do conhecimento comum. O modelo aqui apresentado é um exercício mental, conceitual, fazendo uma série de simplificações e removendo elementos que só tornariam a visualização mais complexa. Para entender o exemplo descrevo aqui dois elementos: Relé, é um interruptor eletromecânico. A alavanca de contato se movimenta e fecha o circuito quando uma corrente elétrica percorre as espi