How to pass a variable from ajax to an open web using location.href

0

Very good, I have an ajax function that calls a file and returns a variable, once I have that variable that is "objJson", I would like to open a page and pass that variable objJson. I hope you understand.

function login(){
usuario=$('#idUsuario').val(); 
clave=$('#idClave').val(); 

var parametros = {
        "ap":"4c",
        "usuario":usuario,
        "clave":clave,
    }

    $.ajax ({
        data: parametros,
        url: "/l/php/login.php",
        type: "POST",

    success: function(data){
        var objJson=JSON.parse(data);
        location.href ='principal.html';
    });
}

Thank you very much

    
asked by Lorenzo Martín 20.09.2017 в 13:40
source

2 answers

1

You have at least two options:

You could pass it in the URL and then get it in the new page:

location.href='principal.html?objJson=' + data;

Assuming that both pages are in the same domain, you could pass it through the localStorage:

localStorage.setItem('objJson',data);
location.href='principal.html;

And on the destination page do a simple

let objJson=JSON.parse(localStorage.getItem('objJson'));

Example of the first case:

let direccion = 'http://www.example.com/principal.html';

let objJson={hola:"texto"};

direccion+= '?objJson=' + JSON.stringify(objJson);

// En la página destino:
let url = new URL(direccion); // En la página destino sería location.href
let param = JSON.parse(url.searchParams.get('objJson'));
console.log(param.hola);
    
answered by 20.09.2017 / 13:57
source
1

You should send the variable from the same URL. You can do it in the following way:

function login(){
 usuario=$('#idUsuario').val(); 
 clave=$('#idClave').val(); 

 var parametros = {
    "ap":"4c",
    "usuario":usuario,
    "clave":clave,
 }

 $.ajax ({
    data: parametros,
    url: "/l/php/login.php",
    type: "POST",

 success: function(data){
    var objJson=JSON.parse(data);
    location.href ='principal.html?variable=' + objJson;
 });
}
    
answered by 20.09.2017 в 13:54