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.
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:
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.
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 |
|
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
Post a Comment