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

后端 未结 3 1097
广开言路
广开言路 2021-01-08 01:09

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?

相关标签:
3条回答
  • 2021-01-08 01:22

    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()
        }
    }   
    
    0 讨论(0)
  • 2021-01-08 01:44

    You can do that easily in C++ as Qt5 has native support for JSON. Check the following answer for the example:

    How to create/read/write JSon files in Qt5

    0 讨论(0)
  • 2021-01-08 01:45

    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.

    0 讨论(0)
提交回复
热议问题