0

我正在尝试从方法(pollServiceForInfo)返回一个 JSON 对象,但是当我在方法完成后提醒它时,它似乎“丢失”了。我知道这是一个范围界定问题,但是我对如何继续感到困惑。洞察力将不胜感激。

var id=null;
var jsonData = JSON.stringify( {searchRequest:{coordinates: "1,2,3 1,2,3 1,2,3 1,2,3 1,2,3"}} );
$.post("rest/search",jsonData, function(json){
    id = json.searchResponse.id;
})
.error(function(jqXHR, textStatus, errorThrown){
    alert("obj.responseText: "+jqXHR.responseText + "  textStatus: "+textStatus+"  errorThrown: "+errorThrown);
})
.success(function(data, status, obj){
    // process initial request
    var json = pollServiceForInfo(id);  // method below

    alert(json);  // says undefined
});



var pollServiceForInfo = function(id){
    //alert('id in pollServiceForInfo '+id);    
    var jsonResults;
    $.get("rest/poll/"+id,function(data){
        jsonResults = data.pollResponse;

    }).error(function(){ 
        alert('returning error');
        return "error";
    }).success(function(){
        alert('returning data '+jsonResults);
        return jsonResults;  // is lost after it's returned
    });
};
4

2 回答 2

0

您不能有效地从异步函数返回。改为这样做:

var pollServiceForInfo = function(id, callback){
    //alert('id in pollServiceForInfo '+id);    
    var jsonResults;
    $.get("rest/poll/"+id,function(data){
        jsonResults = data.pollResponse;

    }).error(function(){ 
        alert('returning error');
        callback("error");
    }).success(function(){
        alert('returning data '+jsonResults);
        callback(jsonResults);  // is lost after it's returned
    });
};

pollServiceForInfo(id, function(json) {
    alert(json);
});
于 2012-05-23T23:21:50.043 回答
0

您正试图从成功回调中返回。您想要的是从 pollServiceForInfo() 中返回,如下所示:

var pollServiceForInfo = function(id){    
    var jsonResults;
    $.get("rest/poll/"+id,function(data){
        jsonResults = data.pollResponse;
    }).error(function(){ 
        alert('returning error');
        jsonResults = "error";
    }).success(function(){
        alert('returning data '+jsonResults);        
    });

    return jsonResults;
};
于 2012-05-24T00:42:41.280 回答