Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use JavaScript to get JSON data from the server inside my qt app?

Tags:

qt

qml

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?

like image 457
jstice4all Avatar asked Aug 13 '14 04:08

jstice4all


People also ask

How JS store data from JSON file?

If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.

What is valid JSON?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.


2 Answers

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()
    }
}   
like image 145
astre Avatar answered Oct 25 '22 19:10

astre


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.

like image 44
Arnout Avatar answered Oct 25 '22 19:10

Arnout