异步xmlhttprequest外部的响应数据

时间:2019-02-18 10:49:52

标签: javascript ajax asynchronous xmlhttprequest

我想知道如何将来自异步xmlhttprequest的响应数据存储在请求完成后要使用的变量中?这是最佳实践吗?还是我应该根据请求内部的响应数据进行所有操作?

我认为xmlhttprequest应该仅返回数据,并且与数据相关的其他操作应在请求完成后进行。还是我弄错了?

我无法发布整个代码,但希望注释能够解释我想要做什么。在下面的示例中,我向天气预报API发出了同步获取请求。响应中包含超过24小时的天气预报,但我只计划使用响应中的3个预报来覆盖今天的天气。但是,每个天气预报都包含我需要的符号ID,以便获取报告的正确天气图像。这意味着我将必须存储这3个ID,以便我可以构建正确的URL.s以获得相应的预测图像。即使这可以同步工作,但我还是建议按照异步方式进行。

这里的问题是我需要将来自xmlhttprequest的响应数据存储在某个变量中,以便可以使用响应中的符号ID来为相应的天气图像建立URL:s。

let baseURL = 'https://api.met.no/weatherapi';
let forecastBase = 'locationforecast/1.9';
let latitude = 'lat=40.730610';
let longitude = 'lon=-73.935242';
let forecastURL = baseURL + '/' + forecastBase + '/' + '?' + latitude + '&' + longitude;
let weatherData;

const xhttp = new XMLHttpRequest();
  document.addEventListener("DOMContentLoaded", function(event) { 
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {  
          // GET the forecast reports and the symbol id for the weather images          
    }
  }
  xhttp.open('GET', forecastURL, false);
  xhttp.send();


  // Get weather images with the symbol id from the forecasts from https://api.met.no/weatherapi/weathericon/1.1/?symbol=5&content_type=image/png
  });

0 个答案:

没有答案