Javascript 从ajax的事件onreadystatechange返回Json对象
我向一个json字符串发出ajax请求,然后对其进行解析,我想将这个名为“encuesta”的json对象从event onreadystatechange返回到“jacu”变量以全局访问 这是我的密码:Javascript 从ajax的事件onreadystatechange返回Json对象,javascript,ajax,json,xmlhttprequest,onreadystatechange,Javascript,Ajax,Json,Xmlhttprequest,Onreadystatechange,我向一个json字符串发出ajax请求,然后对其进行解析,我想将这个名为“encuesta”的json对象从event onreadystatechange返回到“jacu”变量以全局访问 这是我的密码: window.onload= function(){ enter code here`tabla = document.getElementById("pregunta"); enter code here`jencu= ajax("GET","datos/encuesta.json",t
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();
}
如果希望encuesta全局可访问,则应在函数外部声明它 你能解释一下什么对你来说不起作用吗?我无法全局访问json对象@mattpileggippossible的副本,尽管json.parse对我来说运行良好,但尝试$.parseJSON(encuesta)可能不是个坏主意。我的评论不是关于主要问题,而是关于优化逻辑。您必须将if(que==“lee”){}语句放在AJAX调用之外,并在对AJAX进行任何调用之前进行此检查。为什么?因为当que!=“李”。换句话说:首先检查que==“lee”,如果是,则继续,如果不是,则继续-以return(error或任何die语句)终止。您能给我举个例子吗?只需键入var encuesta=“”;在window.onload函数之前。它现在是一个全局变量,然后在OnReadyState函数中覆盖(给定新值),并在代码的其余部分中已知。