extract function variable within JavaScript call

0

I have a call with JavaScript and I want to manipulate this data further in other functions, as I could do .. this is an example of my code ...

$.get("https://api.test.com/",
function (data) {
variableGlobal = data[0].one;
}, "json");

also the call with AJAX works for me;

$(function() {
    $(document).ready(function(){
        $.ajax({
            url: 'https://api.test.com/',
            type: 'GET',
            dataType: 'JSON',
            success: function(data){
                var variableGlobal = data[0].one;

            }
        });
    });
});

What I want is to be able to use variableGlobal with any of the two calls later ... in other functions ect ..

Thank you!

    
asked by Gabriela 06.05.2018 в 03:52
source

1 answer

0

You can define it outside of any function and it will be global, the value you take then will depend on how you modify it

var variableGlobal = "Valor Inicial";
var reloj = Date.now();

console.log(Date.now() - reloj, "recien declarada", variableGlobal);

setTimeout(function(){
    variableGlobal = "5 segundos timeout";
    console.log(Date.now() - reloj, "a los 5 segundos de empezar", variableGlobal);
},5000);

$.get("https://api.test.com/",
function (data) {
   variableGlobal = data[0].one;
   console.log(Date.now() - reloj, "$.GET", variableGlobal);
}, "json");

// tambien la llamada con AJAX me funciona;

$(function() {
    $(document).ready(function(){
        $.ajax({
            url: 'https://api.test.com/',
            type: 'GET',
            dataType: 'JSON',
            success: function(data){
                variableGlobal = data[0].one;
                console.log(Date.now() - reloj, "$.ajax : success", variableGlobal);
            },
            complete: function(data){
                variableGlobal = "COMPLETE";
                console.log(Date.now() - reloj, "$.ajax : complete", variableGlobal);
            },
            error: function(data){
                variableGlobal = "ERROR";
                console.log(Date.now() - reloj, "$.ajax : error", variableGlobal);
            }
           
        });
    });
});

function cambiarValor(){
   variableGlobal = "valor cambiado";
   console.log(Date.now() - reloj, "dentro de cambiarValor()", variableGlobal);
}

console.log(Date.now() - reloj, "casi fin del codigo", variableGlobal);

cambiarValor();

console.log(Date.now() - reloj, "fin del codigo", variableGlobal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Edit

I added a "clock" that counts the milliseconds for each console.log.

Notice how the ajax calls (and changing the value of the variable) are out of sync (asynchronous) with respect to the linear code.

    
answered by 06.05.2018 / 04:53
source