Javascript trans data to qml have problems



  • ./
    main.qml
    Test.qml
    In Test.qml
    @import QtQuick 2.0
    import QtQuick.LocalStorage 2.0 as Sql
    QtObject{
    id:weatherInfo
    property var db: null
    property var result: []
    function getCurWeatherInfo(cityname)
    {
    var doc = new XMLHttpRequest();
    //a function to be called automatically when the readyState changed
    var cityID = getCityIDs(cityname);
    //result=new Array;
    doc.open("GET", qsTr("xxxxx.html").arg(cityID));
    //weatherArray[0] = new Array;
    doc.onreadystatechange = function() {
    if (doc.readyState == XMLHttpRequest.DONE) {
    var jsonObject = eval('(' + doc.responseText + ')');
    result['temp']=jsonObject['weatherinfo']['temp']
    result['city']=jsonObject['weatherinfo']['city']
    console.log(result['temp']);
    console.log(result['city']);
    }
    }
    doc.send();
    }
    }
    }
    @

    In main.qml
    @
    Rectangle{
    id:rect
    Test{
    id:testItem
    }
    Button{
    id:someButton
    onClicked:{
    testItem. getCurWeatherInfo(cityname)
    console.log(testItem.result['temp'] + " "+ result['city'])
    }
    }
    }
    @
    my quesion is that :
    why in main.qml output:
    undefined undefined
    in Test.qml output:
    27 city

    it is very confusing , I have set result property in Test.qml, it should be a global var in Test.qml but why in func getCurWeatherInfo() it cannot be updated.

    PS: it is a trick about javascript asynchronous function???
    I need everyone's help, thanks



  • I use a way to solve this problem, use result as a parameter in getCurweatherInfo(cityName, result),it can be ok.
    PS: it seemed very silly,because I am a javascript and qml freshman.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.