Passing JS values to another HTML page

Asked

Viewed 33,846 times

5

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

index.html
receive variable.html

Like, any way to save that value and page to the other page without having to use the php as a basis.

  • Localstorage, cookies, indexedDB, Websql and GET parameters are the forms I know. From one searched in each, we always have something to learn =) (recommend the localstorage, simple and ie8+)

  • Related http://answall.com/questions/58958/passar-variável-php-para-javascript

2 answers

9


Yes, it is possible to pass values by url.

Let me give you an example with javascript.

In index.html, I create a function that takes a parameter, which is the value I want to pass 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);

On your receiving page_variable.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");

  • 1

    I believe that returning Undefined is more correct than false when the parameter is not found.

  • merman bixo, very good @alex-Sander... Innovative!

8

Using the new HTML5, it is possible to write data (only of type string) no client, no need to use any server language (ASP.NET, MVC, PHP, etc.).

HTML5 has several Storage modes (support for these is in html5rocks.comin English. One 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.