I'm creating my first app that uses an external datasource. I've already built a remote RESTful service that's working as expected. Now I'm trying to access and use the data in the iPhone app. Here's the basic (truncated) layout for the page:
exports.Preview = function(searchCriteria, searchData) { ... Ti.API.info("mCount1: " + mCount); getCount(searchCriteria, searchData); Ti.API.info("mCount3: " + mCount); ... function getCount(searchCriteria, searchData) { var url = "http://www.myDomain.com/service/myService.svc/GetCount/searchCriteria/searchData"; var json var xhr = Ti.Network.createHTTPClient({ onload: function() { json = JSON.parse(this.responseText); Ti.API.info("json.count: " + json.count); mCount = json.count; Ti.API.info("mCount2: " + mCount); } }); xhr.open("GET", url); xhr.send(); } )The service returns a very simple JSON string which looks exactly like this:
{"count":12}You'll notice the various Ti.Info lines I'm using to track the value of the global variable mCount. Based on how this code is layed, I expected to see something like this in the Console Window:
[INFO] mCount1: 0 [INFO] json.count: 12 [INFO] mCount2: 12 [INFO] mCount3: 12But instead, this is what I get:
[INFO] mCount1: 0 [INFO] mCount3: 0 [INFO] json.count: 12 [INFO] mCount2: 12I really don't understand the order in which things are happening here. It appears as if the block inside the onload: function() doesn't execute until just before the window loads? If so, how can I get and use the data from the service? Will I need to build the entire page inside this onload: function()?
Thanks for any insights you can provide!
Casey
Titanium Studio 2.1.0, SDK 2.1.0, iPhone
1 Answer
HTTP calls are handled asynchronously. So the code in your load function doesn't execute until the response from your web service returns. Therefore count3 gets printed before count2. If you want to do something with the count, you have to do it in the load function of your http call.
Your Answer
Think you can help? Login to answer this question!