原文: http://wiki.appcelerator.org/display/guides/Working+with+Remote+Data
要点
* 怎样通过HTTPClient和远程交互
* 怎样取得XML或JSON格式的数据
* 怎样下载和上传文件
* 使用SOAP网络服务的必要步骤
* 使用HTTP头
Titanium中的远程数据
通过Titanium.Network 命名空间使用HTTPClient 对象来进行HTTP数据交互。HTTPClient的API类似于网页浏览器中的XMLHTTPRequest 对象,如果你做过浏览器中的Ajax程序(像Dojo 或jQuery库,他们用XMLHTTPRequest),就会对HTTPClient 很熟悉。
HTTPClient和RESTful资源
可以用HTTPClient和各种流行的网络服务交互,最简单的就是REST-style的网络服务。讲解RESTful 网络服务超出了本书的范围,你可以看这里。对我们来说,只要理解“resource”只是网络上的bit数据而已,用URI指定。还有,手机程序可以用HTTP GET 和POST请求 和网络交互(HTTPClient支持绝大多数的HTTP交互 )。
GET请求
做一个GET请求(或者其他类型的请求)包括3步:
* 创建 HTTP Client
* 打开HTTP链接,指向特定源
* 发送HTTP请求
使用Titanium的JS的API:
var xhr = Ti.Network.createHTTPClient(); // returns an instance of HTTPClient
xhr.open('GET','http://www.google.com');
xhr.send();
仅仅发送请求没什么用。需要后台响应,由response body支持。指定回调函数来访问数据。有很多回调函数。最常用的是onload和onerror。
var xhr = Ti.Network.createHTTPClient(); // returns an instance of HTTPClient
xhr.onload = function(e) {
//this fires when your request returns successfully
//this.responseText and this.responseXML
//will be used often
};
xhr.onerror = function(e) {
//this fires if Titanium/the native SDK cannot successfully retrieve a resource
};
xhr.open('GET','http://www.google.com');
xhr.send();
POST请求
标准的HTML形式。一般用POST (或PUT)请求。Titanium 有简单的方法发送POST body请求。可以自动分析JS对象转化成form-encoded的POST 参数。
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function(e) {
//handle response
};
xhr.open('POST','http://www.myblog.com/post.php');
xhr.send({
title:'My awesome blog',
body:'Today I met Susy at the laundromat. Best day EVAR\!'
});
也可以发送任何形式的文本内容:
xhr.send('<some><xml><data></data></xml></some>');
使用数据
在生命周期事件中,你会解析从后台发回的数据。HTTPClient对象。