Why I can't assign the "th" variant in this JS function?



  • I want to get JSON data from the Internet,and I write a js function to load the JSON data to my ListModel.But there is an unexpected error, which is ,var "th" can't be assigned in onreadystatechange function.What happened?
    Here is the function:
    function getPictureURLByID(idstr){
    var beforeID = "http://ting.baidu.com/data/music/links?songIds=";
    var sea = beforeID + idstr; // "idstr" is a id string that I get from another JS function,such like:2152968,107184439,91590745,...
    var th = "";

       var here = new XMLHttpRequest();
       here.open("GET",sea);
       here.onreadystatechange=function(){
           if (here.readyState == XMLHttpRequest.DONE){
               var there = JSON.parse(here.responseText);   
               th = there.data.songList[0].songPicSmall; //"th" is assigned to the URL of certain image
               console.log(th);  // this prints something like :http://a.hiphotos.baidu.com/ting/pic/item/cdbf6c81800a19d80b7d421131fa828ba61e46ac.jpg
           }
        }
       here.send();
       console.log(th);  //while this prints nothing,just an empty string
       return th;  
    

    }



  • Can anyone help?



  • You should exercise some patience. Typical rule in the past was to wait at least a day or a couple of them.

    Unfortunately, I cannot help you with this. Possibly a stupid question, can't you use a debugger?
    In C++ I would simply set a break point around and check if the program code is executed as expected.



  • I agree with @koahnig . Be patient.

    Regarding your question, XMLHttpRequest performs an asynchronous request. "th" is empty right after send() because onreadystatechange wasn't triggered yet. You'd better have a callback function.

    function getTh(onThReady){
       var here = new XMLHttpRequest();
       here.open("GET",sea);
       here.onreadystatechange=function(){
           if (here.readyState == XMLHttpRequest.DONE){
               var there = JSON.parse(here.responseText);   
               onThReady(there.data.songList[0].songPicSmall);
           }
        }
       here.send();
    }
    ...
    getTh(function(th){ console.log(th); });


  • @koahnig Well,I didn't think of using a debugger. I just can't imagine such an assignment problem have to use a debugger. Right now ,I'm going to use that.



  • @Leonardo such a small but knotty thing...


Log in to reply
 

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