【问题标题】:HTTPClient call is not returning correct JSON data in Appcelerator Titanium appHTTPClient 调用未在 Appcelerator Titanium 应用程序中返回正确的 JSON 数据
【发布时间】:2017-01-16 04:49:16
【问题描述】:

每次我尝试从 JSON 中获取信息时都会出错。

function buscar(e){
    var url = 'https://www.dotscancun.com/createjson.php?id=100001';
    var xhr = Ti.Network.HTTPClient({
    onerror: function(e){
        Ti.API.info(this.responseText);
        Ti.API.info(this.status);
        Ti.API.info(e.error);
        },
        timeout: 5000
    });   
    xhr.open('GET',url);
    xhr.send();
    xhr.onload = function(){ 
        var json = JSON.parse(this.responseText); 
        alert(json);
    };
};

这是代码。

错误是:

[LiveView] Client connected
[ERROR] :  TiHTTPClient: (TiHttpClient-8) [1340,1340] HTTP Error (java.io.IOException): 404 : Not Found
[ERROR] :  TiHTTPClient: java.io.IOException: 404 : Not Found
[ERROR] :  TiHTTPClient:    at ti.modules.titanium.network.TiHTTPClient$ClientRunnable.run(TiHTTPClient.java:1217)
[ERROR] :  TiHTTPClient:    at java.lang.Thread.run(Thread.java:818)

错误404表示该网站不存在,但是如果你复制它的url它可以工作,是什么问题?

【问题讨论】:

    标签: javascript java json titanium appcelerator


    【解决方案1】:

    您在问题中发布的错误消息与您的 JSON 查询无关。相反,它与您的 Android 设备日志输出有关。所以你可以直接忽略那个调用。

    你写错了,因为:

    • 您没有创建正确的 HTTPClient 对象。您正在使用 Ti.Network.HTTPClient 而不是 Ti.Network.createHTTPClient
    • onload 方法应该在 open() 调用之前定义。

    这是您问题的正确代码:

    function buscar(e){
        var url = 'https://www.dotscancun.com/createjson.php?id=100001';
    
        var xhr = Ti.Network.createHTTPClient({
            onerror: function(e){
                Ti.API.info(this.responseText);
                Ti.API.info(this.status);
                Ti.API.info(e.error);
            },
    
            timeout: 5000,
    
            onload : function(){
                alert(this.responseText);
    
                // parse it for further use
                var tempJSON = JSON.parse(this.responseText);
            }
        });
    
        xhr.open('GET',url);
        xhr.send();
    }
    

    【讨论】:

    • 请记住,当请求没有返回 JSON 时,应用程序会崩溃。创建一个使用 try 和 catch 解析 JSON 的辅助函数,这样更安全。
    • @Gerben,是的,但没有在代码中提及它只是因为让该用户清楚简单地了解如何使用客户端调用。我相信他可以自己使用try-catch。这就是为什么我也没有删除超时的原因,因为它并不总是确定在 5 秒内下载了图片,所以这将有助于他进一步理解事情。
    猜你喜欢
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多