retornar objeto Json do evento onreadystatechange do ajax
-
21-12-2019 - |
Pergunta
faço uma solicitação ajax para uma string json e depois analiso, quero retornar esse objeto Json chamado "encuesta" do evento onreadystatechange para a variável "jacu" para acessar globalmente
aqui está meu código:
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();
}
Solução
Se você deseja que a encuesta seja acessível globalmente, você deve declará-la fora da sua função.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow