c++ - 如何使用 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
解析功能。但仍有一些不正确的地方。
感谢您指出解决此问题的正确方向。
解决方案
下面回答我的问题。我没有正确读取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()
}
希望有帮助!
推荐阅读
- docker - Redmine cron 作业在 docker 中获取电子邮件 (redmine:email:receive_imap)
- python-3.x - 绘制不同 CNN 分类器的多重验证的准确性
- javascript - 如何测试承诺是否返回正确的值
- spring - 如何捕获来自 POST 的值以执行存储在 Spring Boot 中的过程
- c# - 如何正确读取 C# 中 .Any 函数的方法签名
- python - 摄氏到华氏方法不起作用
- c - 使用 fatfs 的 f_printf 的断言错误,但 f_write 工作正常
- java - 如何找到二维数组的总数?
- macos - 为什么“last”的输出显示历史的时间少于我拥有笔记本电脑的时间?
- .net - 如何在数据表的每一列中获取大于 0 的最小字符串长度