Passing JS values to another HTML page

4

Is it possible for javascript to pass a variable whether it is global or not from an HTML page to another HTML?

index.html
recibaria.html

Type, some way to save this value and move it to the other page without having to use php as a basis.

    
asked by anonymous 19.07.2015 / 17:58

2 answers

5

Yes, it is possible to pass values by url.

I'll give you an example with javascript.

In index.html, I create a function that gets a parameter, which is the value I want to move to another page. When running it redirects to the page that will receive the variable, passing the value by url.

var passaValor= function(valor)
{
    window.location = "recebe_variavel.html?minhaVariavel="+valor;
}


var valorQueEuQueroPassar = 123;

 passaValor(valorQueEuQueroPassar);

In your page receive_variavel.html, I use a function that reads the url in search of its variable in the url.

// função pra ler querystring
function queryString(parameter) {  
              var loc = location.search.substring(1, location.search.length);   
              var param_value = false;   
              var params = loc.split("&");   
              for (i=0; i<params.length;i++) {   
                  param_name = params[i].substring(0,params[i].indexOf('='));   
                  if (param_name == parameter) {                                          
                      param_value = params[i].substring(params[i].indexOf('=')+1)   
                  }   
              }   
              if (param_value) {   
                  return param_value;   
              }   
              else {   
                  return undefined;   
              }   
        }

var variavel = queryString("minhaVariavel");
    
19.07.2015 / 20:00
7

Using the new HTML5, you can write data (only type string ) on the client, without having to use any language on the server (ASP.NET, MVC, PHP, etc.).

HTML5 has several Storage modes (support for them can be found in html5rocks.com in English One of them is localStorage, the other is sessionStorage, use them like this:

<script>
  var dados = JSON.stringify($('input').val());
  sessionStorage.setItem('chave', dados );

  //... depois ...

  var dadosArquivados = JSON.parse(sessionStorage.getItem('chave'));
</script>
    
20.07.2015 / 02:42