Simplify Date Request via json

Asked

Viewed 49 times

0

can I return the value of a variable outside the block "in case it would be the variables serverTime and off", say so I can use in another function or in my html code.

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
    var dateHeader = xmlhttp.getResponseHeader('Date');

    // Basta armazenar a hora atual no dispositivo para fins de exibição 
    deviceTime = moment();

    // Transforme o campo do cabeçalho "Data:" em um objeto "momento",
    serverTime = moment(new Date(dateHeader)); // Read

    // Armazene as diferenças entre a hora do dispositivo e a hora do servidor
    off = serverTime.diff(moment());

    return
}


xmlhttp.open("HEAD", window.location.href);
xmlhttp.send();

Just one note, I’m using this script to pick up the current server time.

Thank you!!!!

  • 1

    But the variables were declared globally, you can already use them anywhere in the code.

  • So, what I don’t understand, I tested a alert(serverTime); after the line xmlhttp.send(); and is not passing.

  • And what you showed in Alert?

  • If I put it inside the scope it works normal showing the date pretty, but outside it shows nothing, I gave an F12, I’m trying to understand the errors here

  • So it’s because the object Xmlhttprequest() generates an asynchronous code, that is, it depends on the return of the server that can be immediate, time-consuming or even never occur, to return the answer.

  • you can tell me if there’s any other way to do it ?

  • 1

    haha did different, called my other function within the scope, there before the Re-turn. There funfou right. Anyway thanks for the attention. Great!!!! Hug!!!

Show 2 more comments

1 answer

0


The solution I found was to call my other function within the scope, so my other function was able to receive the value of serverTime.

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
    var dateHeader = xmlhttp.getResponseHeader('Date');

    // Basta armazenar a hora atual no dispositivo para fins de exibição 
    deviceTime = moment();

    // Transforme o campo do cabeçalho "Data:" em um objeto "momento",
    serverTime = moment(new Date(dateHeader)); // Read

    // Armazene as diferenças entre a hora do dispositivo e a hora do servidor
    off = serverTime.diff(moment());

    //chamei a função aqui antes do retorno, e assim ela enxergou a var serverTime;
    metal(); 

    return
}
xmlhttp.open("HEAD", window.location.href);
xmlhttp.send();

Browser other questions tagged

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