I need to get JSON data and load it to a table. As I guess I need some C++ skills for it. But can I do this in plain JavaScript or may be QML?
Asked
Active
Viewed 1.0k times
3 Answers
25
Yes, you can do it purely using javascript API's in QML. Following code works on 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()
}
}

Amit Tomar
- 4,800
- 6
- 50
- 83

astre
- 798
- 6
- 14
-
Thanks. It helped a lot. Please edit your answer. Some parts of your code aren't marked as code. – jstice4all Aug 14 '14 at 05:13
-
I have actually added the code inside the code tags, but its not formatting it properly. Thanks. – astre Aug 14 '14 at 05:29
-
You can format it easily by adding a 4 spaced tab setting to your editor and adding an extra tab before the whole code, then copy paste it here, as I just did – islahul Aug 14 '14 at 06:52
-
-
the disadvantage is the javascript part won't be compiled natively, so it's not good from a security perspective. If it's something important. – Konrad Jun 29 '19 at 06:34
3
If you add the pure-QML JSONListModel to your project, you can use the full power of the View-Model pattern. However, it doesn't support presenting the data before it is fully downloaded.

Arnout
- 2,927
- 16
- 24
-1
You can do that easily in C++ as Qt5 has native support for JSON. Check the following answer for the example:

Community
- 1
- 1

adnan kamili
- 8,967
- 7
- 65
- 125
-
If you would read the question more carefully you understand that I want a javascript/qml solution not C++ one. – jstice4all Aug 14 '14 at 05:11