javascriptajaxjsonxmlhttprequestonreadystatechange

return Json object from event onreadystatechange of ajax


i make a ajax request to a json string and then i parse it, i want to return this Json object called "encuesta" from event onreadystatechange to the "jacu" variable to access globally

heres my code:

window.onload= function(){
 enter code here`tabla = document.getElementById("pregunta");
 enter code here`jencu= ajax("GET","datos/encuesta.json",true,"lee")
 }

function ajax(metodo,url,bolean,que){
   var xhr;
   if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
   }else{ 
       xhr=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xhr.onreadystatechange=function(){

           if (xhr.readyState==4 && xhr.status==200){
              if(que == "lee"){
                encuesta=xhr.responseText;
                  encuesta = JSON.parse(encuesta)
               }
           }
    }

   xhr.open(metodo,url,true);
   xhr.send();
}

Solution

  • If you want encuesta to be accessible globally, you should declare it outside your function.