使用HTTPClient和JSON处理远程数据(译)

原文地址:http://docs.appcelerator.com/titanium/2.1/index.html#!/guide/Handling_Remote_Data_with_HTTPClient_and_JSON-section-29004823_HandlingRemoteDatawithHTTPClientandJSON-json.txt%28fromourtargetURLhttps%3A%2F%2Fraw.github.com%2Fappcelerator%2FDocumentationExamples%2Fmaster%2FHTTPClient%2Fdata%2Fjson.txt%29

 Titanium.Network.HTTPClient框架

var url = "https://www.appcelerator.com";
var xhr = Ti.Network.createHTTPClient({
    onload: function(e) {
        // this.responseText holds the raw text return of the message (used for JSON)
        // this.responseXML holds any returned XML (used for SOAP web services)
        // this.responseData holds any returned binary data
        Ti.API.debug(this.responseText);
        alert('success');
    },
    onerror: function(e) {
        Ti.API.debug(e.error);
        alert('error');
    },
    timeout:5000
});

xhr.open("GET", url);
xhr.send();

创建一个对象保存要访问的URL

创建HTTPClient对象,该对象有2个方法onload和onerror

onload:这个方法将要求从目标URL成功响应,响应数据可以处理使用HTTPClient3种不同的属性类别。

  • this.responseText--处理JSON
  • this.responseXML--处理SOAP或其他XML格式的网络服务。
  • this.responseData--处理二进制数据

onerror:这个方法响应错误信息,

  • this.responseText
  • this.status
  • e.error

实例代码:

Ti.UI.backgroundColor = '#dddddd';

var url = "https://raw.github.com/appcelerator/Documentation-Examples/master/HTTPClient/data/json.txt";
var win = Ti.UI.createWindow();
var table = Ti.UI.createTableView();
var tableData = [];
var json, fighters, fighter, i, row, nameLabel, nickLabel;

var xhr = Ti.Network.createHTTPClient({
    onload: function() {
    // Ti.API.debug(this.responseText);

    json = JSON.parse(this.responseText);
    for (i = 0; i < json.fighters.length; i++) {
        fighter = json.fighters[i];
        row = Ti.UI.createTableViewRow({
            height:'60dp'
        });
        nameLabel = Ti.UI.createLabel({
            text:fighter.name,
            font:{
                fontSize:'24dp',
            fontWeight:'bold'
        },
        height:'auto',
        left:'10dp',
        top:'5dp',
        color:'#000',
        touchEnabled:false
        });
        nickLabel = Ti.UI.createLabel({
        text:'"' + fighter.nickname + '"',
        font:{
            fontSize:'16dp'
        },
        height:'auto',
        left:'15dp',
        bottom:'5dp',
        color:'#000',
        touchEnabled:false
        });

        row.add(nameLabel);
        row.add(nickLabel);
        tableData.push(row);
        }

    table.setData(tableData);
    },
    onerror: function(e) {
    Ti.API.debug("STATUS: " + this.status);
    Ti.API.debug("TEXT:   " + this.responseText);
    Ti.API.debug("ERROR:  " + e.error);
    alert('There was an error retrieving the remote data. Try again.');
    },
    timeout:5000
});

xhr.open("GET", url);
xhr.send();

win.add(table);
win.open();

ti

原文地址:https://www.cnblogs.com/xiaozhanga4/p/2711422.html