Sunday, August 11, 2019

an example of getting something back asynchronously from an XHR in JavaScript

var homepageEvent = function(response) {
   if (response) {
      if (response.currentTarget) {
         if (response.currentTarget.response) {
            var mainstay = JSON.parse(response.currentTarget.response);
            if (mainstay.currentPlayer) {
               if (mainstay.currentPlayer.playerIp) {
                  var layout = document.getElementById('layout');
                  var links = document.getElementById('links');
                  var summary = document.getElementById('summary');
                  if (mainstay.existingGame) {
                     summary.innerHTML = "Alright " + mainstay.currentPlayer.playerIp + ", you
                           are in a game!";
                  } else {
                     layout.style.display = "block";
                     links.style.display = "block";
                     summary.innerHTML = "Welcome " + mainstay.currentPlayer.playerIp + "!
                           Would you care to play?";
                  }
               }
            }
         }
      }
   }
};
var homepageAjax = function (url) {
   var homepageXhr = new XMLHttpRequest();
   homepageXhr.addEventListener("load", homepageEvent);
   homepageXhr.open("GET", url, true);
   homepageXhr.send();
};
function PrepHomePage() {
   homepageAjax('/api/values');
}

No comments:

Post a Comment