范围问题:价值丢失

时间:2012-05-23 23:09:04

标签: jquery scoping

我正在尝试从方法(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
    });
};

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分: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;
};