首页 > 解决方案 > 如何使用 XMLHttpRequest 在 QML 中正确设置 API 调用

问题描述

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

我遇到的问题是我无法让 API 调用正常工作。在为您在下面看到的一些城市设置了一个最小示例之后,它应该在城市旁边出现天气符号,但它没有发生。可以在此处找到图标列表。为了完整起见,可以在此处找到 MVE 的源代码。

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

这就是正在发生的事情

当前的

这是预期的

预期的

JSON可以在此处和下方找到典型的 API响应:

{
  "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()
}

为了解决这个问题,我查阅了几个来源,首先:官方文档和相关功能。我相信它设置正确,但我添加了完整性参考。我也遇到了这个解释如何简单地应用XMLHttpRequest的。此外,我更深入地研究了这个问题以找到解决方案,并咨询了这个问题,其中还解释了如何应用JSON解析功能。但仍有一些不正确的地方。

感谢您指出解决此问题的正确方向。

标签: c++jsonqtxmlhttprequestqml

解决方案


下面回答我的问题。我没有正确读取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()
}

希望有帮助!


推荐阅读