2013-10-18 4 views
1

저는 원격 PHP 파일과 상호 작용하여 데이터를 검색하는 작은 Android 앱을 개발하기 위해 Titanium SDK를 사용하고 있습니다. HTTPClient에서 데이터를 반환하기 전에 FOR 루프가 실행되므로 'myTest'가 비어 있고 'tblListing'에 아무 것도 추가되지 않습니다.Titanium, HTTPClient 응답을 기다립니다.

같은 스레드에서 다른 작업의 실행을 지연시키지 않고 HTTPClient에서 데이터가 반환 될 때까지 FOR 루프 대기를 만들 수 있습니까? 'jsonPOST'함수는 앱의 여러 요소에 대한 다양한 데이터를 검색하는 데 사용되며 동적으로 유지되어야합니다.

답변

2

데이터가 HTTPClient에 수신되면 함수를 호출 할 수 있도록 콜백 매개 변수가 사용되었습니다. 이렇게하면 jsonPOST 기능을 동적으로 유지할 수 있습니다.

function jsonPOST(inAction, inParams, inCallback) { 

     var xhr = Ti.Network.createHTTPClient({ 
      onload : function(e) { 
       Ti.API.info("Received text: " + this.responseText); 
       var reply = JSON.parse(this.responseText); 
       inCallback(reply); 
      }, 
      onerror : function(e) { 
       Ti.API.debug(e.error); 
       alert('error'); 

       return false; 
      }, 
      timeout : 8000, // in milliseconds 
     }); 

     var sendData = { 
      'action' : inAction, 
      'json' : JSON.stringify(inParams) 
     }; 
     xhr.open('POST', "http://domain.com/file.php"); // url redacted 
     xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
     xhr.send(sendData); 
    } 

function processListing(inJson) { 
    for (i in inJson) { 
     tblListing.appendRow({ 
      title : inJson[i].listingTitle, 
      id : inJson[i].listingID 
     }); 
    } 
} 

jsonPOST('getListing', null, processListing); 
0

루프는 XHR 객체의 onload 속성에 바인딩되는 함수에 있어야 다음 HttpClient를가 ansynchronous 작동

function jsonPOST(inAction, inParams) { // jsonPOST is a global function 
    var xhr = Ti.Network.createHTTPClient({ 
     onload : function(e) { 
      Ti.API.info("Received text: " + this.responseText); 
      for (i in this.responseText) { 
       tblListing.appendRow({ title: myTest[i].title, id: myTest[i].id }); 
      } 
      return this.responseText; 
     }, 
     onerror : function(e) { 
      Ti.API.debug(e.error); 
      alert('error'); 
      return false; 
     }, 
     timeout : 8000, // in milliseconds 
    }); 

    var sendData = { 
     'action' : inAction, 
     'json' : JSON.stringify(inParams) 
    }; 

    xhr.open('POST', "http://domain.com/file.php"); // url redacted 
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
    xhr.send(sendData); 
} // end. jsonPOST() 

var myTest = jsonPOST('getlisting'); // only need to pass first param in this instance 

참고. 요청을 보내고 데이터를 기다리지 만 호출 스크립트는 계속 실행됩니다.

관련 문제