PhoneGap: Getting Data from a Server

Well your application would be pretty useless if you couldn't get data from a remote server now wouldn't it? Luckily since your PhoneGap application is running off of the file:// protocol it isn't limited by the same origin policy. This means we can request data using XmlHttpRequest from any domain.

I'm going to give you an example of searching for all tweets that mention PhoneGap that demonstrates this ability without the use of any extra JavaScript library like jQuery or Dojo.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
function loadTweets() {
var request = new XMLHttpRequest();
request.open("GET", "http://search.twitter.com/search.json?q=phonegap", true);
request.onreadystatechange = function() {//Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var tweets = JSON.parse(request.responseText);
var data = "<table cellspacing='0'>";
var tableClass;
for (i = 0; i < tweets.results.length; i++) {
if (i % 2 == 0) {
tableClass = 'tweetOdd';
}
else {
tableClass = 'tweetEven';
}
data += "<tr style='border: 1px solid black'>";
data += "<td class='" + tableClass + "'>";
data += "<img src='" + tweets.results[i].profile_image_url + "'/>";
data += "</td>";
data += "<td class='" + tableClass + "'>";
data += "<b>" + tweets.results[i].from_user + "</b><br/>";
data += tweets.results[i].text + "<br/>";
data += tweets.results[i].created_at;
data += "</td>";
data += "</tr>";
}
data += "</table>";
var twitter = document.getElementById("latestTweets");
twitter.innerHTML = data;
}
}
}
console.log("asking for tweets");
request.send();
}
tweets.js This Gist brought to you by GitHub


So that is the example in a nutshell. It isn't very different from your normal XHR call except for one line that I need to bring to your attention:
if (request.status == 200 || request.status == 0) {
Most of the time you are just looking for the 200 status code you also need to accept the status code of 0 as also OK. Sometimes when you are requesting data via XHR from the file:// protocol you will get a 0 status code. As I said that is perfectly normal and you should treat it as a 200 and move on with your application.

Much of the rest of this code is just building up a HTML string I can do an insert into a div I've set aside for displaying the tweets. Just wanted to show everyone how easy it is to communicate with a remote server.

Comments

Popular posts from this blog

How to draw an overlay on a SurfaceView used by Camera on Android?

Create EditText with dropdown in android

Android TCP Connection Chat application