我需要获取 JSON 数据并将其加载到表中。我想我需要一些 C++ 技能。但我可以用纯 JavaScript 或 QML 来完成此操作吗?
最佳答案
是的,您可以纯粹使用 QML 中的 javascript API 来完成此操作。以下代码适用于 Qt 5.3.1
import QtQuick 2.0
import QtQuick.Controls 1.2
Item {
width: 300
height: 400
ListModel {
id: model
}
ListView {
id: listview
anchors.fill: parent
model: model
delegate: Text {
text: listdata
}
}
function getData() {
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/Customers_MYSQL.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction(response) {
var arr = JSON.parse(response);
for(var i = 0; i < arr.length; i++) {
listview.model.append( {listdata: arr[i].Name +" "+ arr[i].City +" "+ arr[i].Country })
}
}
Button {
anchors.bottom: parent.bottom
width: parent.width
text: "Get Data"
onClicked: getData()
}
}
关于qt - 我可以使用 JavaScript 从 qt 应用程序中的服务器获取 JSON 数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25278309/