Javascript 如何在方法中从HttpRequest返回结果

Javascript 如何在方法中从HttpRequest返回结果,javascript,ajax,titanium,titanium-mobile,Javascript,Ajax,Titanium,Titanium Mobile,在我的应用程序中,我想用一种方法隔离网络,在我的应用程序中获取ajax是非常常见的。因此,我将Ti.Network.createHTTPClient()放在一个单独的方法中,并使用URL调用它。然后它将解析JSON并返回结果。但是,它总是返回空对象 我假设它在从.onload()方法返回之前重新尝试了方法的结尾 我怎样才能解决这个问题 function getJson(url) { Ti.API.info(" URL is " + url ); var jsonObject ; var xhr

在我的应用程序中,我想用一种方法隔离网络,在我的应用程序中获取ajax是非常常见的。因此,我将Ti.Network.createHTTPClient()放在一个单独的方法中,并使用URL调用它。然后它将解析JSON并返回结果。但是,它总是返回空对象

我假设它在从.onload()方法返回之前重新尝试了方法的结尾 我怎样才能解决这个问题

function getJson(url)
{
Ti.API.info(" URL is " + url );
var jsonObject ; 
var xhr = Ti.Network.createHTTPClient();
xhr.setTimeout(3000);
xhr.onload = function()
{
    var jsonObject = eval('(' + this.responseText + ')');

}
xhr.open("GET" , url); 
xhr.send(); 
Ti.API.info(" passed " );

return jsonObject; 
};

使用回调函数并将其作为参数提供给函数;因为它是异步的。像这样:

function getJson(url, callback) {
    // do your json-ajax stuff
    // where you get the response do:
    callback(response);
}
function callback(response) {
    // do whatever you like with the response
}

您需要在代码中的某个位置设置回调,如下所示:

function getJson(url,callback)
{
Ti.API.info(" URL is " + url );
var jsonObject ; 
var xhr = Ti.Network.createHTTPClient();
xhr.setTimeout(3000);
xhr.onload = function()
{
    callback(jsonObject)

}
xhr.open("GET" , url); 
xhr.send(); 
Ti.API.info(" passed " );
};

function aCallBack(jsonObject){
// the code when the json returns
}