用javascript在码实云平台上,可以在云里编写原生的移动应用。移动应用经常需要访问后台的数据或云上的数据源。下面实例中,我们调用中国天气网的数据接口,获取北京的实时天气情况,并显示在手机上。
Class.create(Mash5.Widget, {
initialize : function (config, params) {
var container = Ti.UI.createView({
width : Ti.UI.FILL,
height : Ti.UI.FILL,
backgroundColor : '#ddd'
});
this.setContentView(container);
container.add(Ti.UI.createLabel({
text: '实时天气',
color: '#000',
font: {fontSize: '24dip'},
top: '10dip',
}));
var box = Ti.UI.createView({
width: '200dip',
height: '200dip',
top: '40dip',
borderRadius: dipToPx(20),
backgroundColor: '#f44',
});
container.add(box);
var info = Ti.UI.createLabel({
text: '正在加载',
color: '#fff',
font: {fontSize: '20dip'},
});
box.add(info);
var json_info = Ti.UI.createLabel({
bottom: '10dip',
text : '获取中国天气网数据...',
color : '#000',
font : {
fontSize : '12dip',
},
});
container.add(json_info);
var url = 'http://www.weather.com.cn/data/sk/101010100.html';
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload: function(e) {
json_info.setText(this.responseText);
var weather = JSON.parse(this.responseText);
info.setText('城市:' + weather.weatherinfo.city + '\n' +
'气温:' + weather.weatherinfo.temp + '\xB0\n' +
'风向:' + weather.weatherinfo.WD + '\n' +
'风力:' + weather.weatherinfo.WS + '\n' +
'湿度:' + weather.weatherinfo.SD + '\n' +
'发布时间:' + weather.weatherinfo.time
);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout: 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();
}
})
为了得到实时的天气数据,我们用到了中国天气网的API。其接口网址是http://www.weather.com.cn/data/sk/101010100.html,用浏览器看下这个网址,可以看到API返回一个json的查询结果。下一步就是用Ti.Network.createHTTPClient准备好onload和onerror的处理,原理和web中常用的Ajax完全相同。onload里面,API的调用结果字串是this.responseText,我们用了JSON.parse(this.responseText)把json字串转换成javascript的对象数据。实际的调用操作分成两步:client.open("GET",url)建立连接,client.send()发出调用请求,就这么简单。用这个方法,可以调用在任意后台或云上的REST API数据服务,企业的业务数据或者是第三方提供的基础服务(天气、股市、比价,等等)。