Javascript HTTPClient调用未在Appcelerator应用程序中返回正确的JSON数据
每次我试图从JSON获取信息时,都会出现一个错误Javascript HTTPClient调用未在Appcelerator应用程序中返回正确的JSON数据,javascript,java,json,titanium,appcelerator,Javascript,Java,Json,Titanium,Appcelerator,每次我试图从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)
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,有什么问题?您在问题中发布的错误消息与您的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时,应用程序将崩溃。创建一个helper函数,通过使用try-and-catch解析JSON,这是一个更安全的方法。@Gerben,是的,但没有在代码中提到它,只是为了让用户清楚简单地了解如何使用客户端调用。我相信他可以自己尝试一下。这就是为什么我没有删除超时的原因,因为它并不总是确定图片是在5秒内下载的,所以它将帮助他进一步理解事情。