如何在 Appcelerator 中从 Rest API 中检索数据

How To Retrieve Data From Rest API In Appcelerator

我不幸要在 Appcelerator 中进一步开发现有的移动应用程序。该应用程序使用远程服务器上的 Rest API 来读取和写入数据。 API 在测试环境和生产环境中运行良好。我需要 post 数据到 API 并读取输出。下面是 API 在执行 POST 命令后的输出示例:

{
    "equipment":
    {
        "result": "create",
        "id": 419213
    },
    "_meta":
    {
        "offset": 0,
        "limit": -1,
        "total_results": 1,
        "url": "http://localhost:8080/api/v1/equipment",
        "utc_start_time": 1459449461115,
        "nano_total_time": 74771
    }
}

我能够成功 post Appcelerator 中的数据。我已经在 CRUD 操作正在作用的数据库中验证了这一点。但是,尽管遵循了过时的 Titanium 文档中的说明,但我无法从进行调用的 httpClient 对象中获取上述数据。

这是我的 Appcelerator 代码:

var payload = "name=atad&asset_number=adtasd&department_id=185080&property_id=10086&designator_id=379828&is_leased=N&is_assignable_asset=N&status=A";
var url = "http://localhost:8080/api/v1/equipment";

var client = Ti.Network.createHTTPClient({
    onload : function(e) {
        Ti.API.info(e); // {}
        Ti.API.info(e.source); // []
        Ti.API.info(JSON.stringify(e.source)); // {}
        Ti.API.info(JSON.stringify(e.source.reponseText)); // null
        Ti.API.info(JSON.stringify(e.source.reponseData)); // null
        Ti.API.info(this); // []
        console.log(JSON.stringify(this)); // {}
        Ti.API.info(JSON.stringify(this.reponseText)); // null
        Ti.API.info(this.reponseData); // null
    }
    ,onerror : function(e){
        Ti.API.info(e);
        alert("error");
    }
});

var auth = 'Basic ' + Ti.App.Properties.getString('auth');

client.open("POST", apiUrl);
client.setRequestHeader('Authorization', auth);
client.setRequestHeader('Content-Type', 'text/plain');
client.send(payload);

控制台输出如下:

[INFO] :   {
[INFO] :       code = 0;
[INFO] :       source = "[object TiNetworkHTTPClient]";
[INFO] :       success = 1;
[INFO] :       type = load;
[INFO] :   }
[INFO] :   [object TiNetworkHTTPClient]
[INFO] :   {"method":"POST","url":"http://localhost:8080/api/v1/equipment"}
[INFO] :   <null>
[INFO] :   <null>
[INFO] :   [object TiNetworkHTTPClient]
[INFO] :   {"method":"POST","url":"http://localhost:8080/api/v1/equipment"}
[INFO] :   <null>
[INFO] :   <null>

这里的文档 http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient 明确表示要使用 this.responseText,但这显然没有给我我需要的结果。我需要从服务器返回的 "id"。

如何读取 post API 调用后从服务器返回的数据?

看看这个模块:https://github.com/jasonkneen/RESTe

它让您的生活更轻松,并为您提供了一种在未来的项目中使用相同语法的好方法!

如果你想保留你的语法(这也很好):

看看这个例子:https://github.com/m1ga/titanium-libraries/blob/master/api.js#L49 和以下几行。它向您展示了如何阅读 JSON。基本上你要等到if (this.readyState === 4) {}里面的onload然后再读this.responseText或者JSON.parse()就可以了。

好像没有定义apiUrl变量?

这可以解释很多或您 当前 的挫败感。

只是 this.responseText

中有错别字