Javascript Can';不要将JSON文件放入变量中

Javascript Can';不要将JSON文件放入变量中,javascript,json,ajax,xmlhttprequest,Javascript,Json,Ajax,Xmlhttprequest,我试图将JSON文件的内容解析为一个名为weatherArray的变量。但是,此变量始终是空数组 让weatherArray=[]; 函数loadDoc(){ var xhttp=newXMLHttpRequest(); xhttp.onreadystatechange=函数(){ if(this.readyState==4&&this.status==200){ weatherArray=JSON.parse(this.responseText); } }; xhttp.open(“GET”

我试图将JSON文件的内容解析为一个名为
weatherArray
的变量。但是,此变量始终是空数组

让weatherArray=[];
函数loadDoc(){
var xhttp=newXMLHttpRequest();
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
weatherArray=JSON.parse(this.responseText);
}
};
xhttp.open(“GET”https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12“,对);
xhttp.send();
}
/*希望在控制台中存储并显示该值*/

控制台日志(weatherArray)在结果返回之前,您正在检查结果。您需要移动该行:

console.log(weatherArray);
进入
onreadystatechange
函数,该函数将在结果到达后检查结果。您还需要调用
loadDoc()
函数(您可能已经这样做了)

让weatherArray=[];
函数loadDoc(){
var xhttp=newXMLHttpRequest();
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
weatherArray=JSON.parse(this.responseText);
控制台日志(weatherArray);
}
};
xhttp.open(“GET”https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12“,对);
xhttp.send();
}

loadDoc()Ajax是异步调用,在调用Ajax调用之前打印数据

我做了一些改变,试试看

让weatherArray=[];
函数loadDoc(){
var xhttp=newXMLHttpRequest();
xhttp.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
weatherArray=JSON.parse(this.responseText);
console.log(this.responseText);
}
};
xhttp.open(“GET”https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12“,对);
xhttp.send();
}
loadDoc();

/*由于希望在控制台中存储和显示值*/
,我想提供一种使用FetchAPI和Promises的替代现代方法

  • 首先从api获取数据
  • 将其转换为json
  • 还债
  • 倾听承诺并将结果记录在回调中
  • 函数loadDoc(){
    返回取回(“https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12")
    .then(res=>res.json())
    }
    loadDoc()。然后((weatherArray)=>{
    控制台日志(weatherArray);
    
    })
    您是否已登录console.logged
    responseText
    以验证服务器是否正在发送返回的内容?您如何知道它是empty?你在哪里测试?在回调之外?@JoãoAraúJo-正如MarkãM指出的,您的
    console.log()
    语句在填充
    weatherArray
    之前执行。XHR是异步的,因此您必须在处理程序中操作和/或记录预期的数据。您可以,但想法是在函数中收集数据,然后将其传递给另一个函数,该函数随后将对数据进行操作。这是JavaScript异步处理模型的本质。研究它,它是JS的基础。是的,一旦你理解它,你会发现它很容易。您对API进行了调用,这需要时间(毫秒),一旦响应到达,函数就会被调用,只有这样您才能使用数据。谢谢!这种替代方案的优点和缺点是什么?缺点是没有多边形填充。主要的优点是可读性和开发经验。它不仅适用于IE(包括手机在内的所有版本),在BlackBery、Opera Mini中也不起作用,更重要的是在Safari iOS 8之前、Safari Mac 7.1之前和Android 4.4.4之前。然而,全球这些平台的总用户不到10%(在某些国家可能更高)。