如何使用 XMLHttpRequest 在 QML 中正确设置 API 调用

How to properly set an API call in QML using XMLHttpRequest

我正在构建一个小天气 API 作为使用 QML 的练习,并使用 OpenWeather 正确操作 API 调用,你可以看到一个典型的 API响应。

我遇到的问题 是无法接通 API 工作电话。在设置了一些城市的最小示例后,您可以在下面看到,在城市旁边应该会出现天气符号,但它并没有发生。为了完整起见,可以找到图标列表 here. Source code of the MVE can be found here

编译器错误:qrc:/main.qml:282: SyntaxError: JSON.parse: Parse error

这就是正在发生的事情

这是预期的

典型的 API JSON 响应可以在 here 及以下找到:

{
  "coord": {
    "lon": -122.08,
    "lat": 37.39
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 282.55,
    "feels_like": 281.86,
    "temp_min": 280.37,
    "temp_max": 284.26,
    "pressure": 1023,
    "humidity": 100
  },
  "visibility": 16093,
  "wind": {
    "speed": 1.5,
    "deg": 350
  },
  "clouds": {
    "all": 1
  },
  "dt": 1560350645,
  "sys": {
    "type": 1,
    "id": 5122,
    "message": 0.0139,
    "country": "US",
    "sunrise": 1560343627,
    "sunset": 1560396563
  },
  "timezone": -25200,
  "id": 420006353,
  "name": "Mountain View",
  "cod": 200
} 

下面是与 API 调用相关的代码片段:

main.qml

// Create the API getcondition to get JSON data of weather
function getCondition(location, index) {
    var res
    var url = "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"
    var doc = new XMLHttpRequest()
    // parse JSON data and put code result into codeList
    doc.onreadystatechange = function() {
        if(doc.readyState === XMLHttpRequest.DONE) {
            res = doc.responseText
            // parse data
            var obj = JSON.parse(res)  // <-- Error Here
            if(typeof(obj) == 'object') {
                if(obj.hasOwnProperty('query')) {
                    var ch = onj.query.results.channel
                    var item = ch.item
                    codeList[index] = item.condition["code"]
                }
            }
        }
    }
    doc.open('GET', url, true)
    doc.send()
}

为了解决这个问题,我查阅了几个资料,首先是:official documentation 和相关函数。我相信它设置正确,但我添加了完整性参考。 我还遇到了 this one,它解释了如何简单地应用 XMLHttpRequest。 此外,我深入研究了问题以找到解决方案,还咨询了 this one,其中还解释了如何应用 JSON 解析函数。但是还是有些不对。

感谢您指出正确的方向来解决这个问题。

在您的代码中,您的 url 显示:"api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"。您需要用实际值替换 {city id}{your api key}

您可以通过在请求中提供实际的城市 ID 和 API 密钥来解决此问题 URL

在我的问题的答案下方。我没有正确阅读 JSON 文件,在控制台记录问题后,解决方案如下。代码从一开始就是正确的,只有响应需要正确审查并且非常详细,因为 JSON 响应有点混乱:

function getCondition() {
    var request = new XMLHttpRequest()
    request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=key', true);
    request.onreadystatechange = function() {
        if (request.readyState === XMLHttpRequest.DONE) {
            if (request.status && request.status === 200) {
                console.log("response", request.responseText)
                var result = JSON.parse(request.responseText)
            } else {
                console.log("HTTP:", request.status, request.statusText)
            }
        }
    }
    request.send()
}

希望对您有所帮助!